如何将asp.net页面的出生日期插入sql server 2008 [英] how to insert date of birth from asp.net page to sql server 2008

查看:111
本文介绍了如何将asp.net页面的出生日期插入sql server 2008的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用



i m using

str="insert into date values('"+TextBox1.Tex)+ "')";
ad=new SqlDataAdapter (str,CT.connect());
       dt = new DataTable();
       ad.Fill(dt);




$。b $ b查询.cs页面但它给出了错误信息..



query in .cs page but it gives error msg..

推荐答案

不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。这可能既解决了当前的问题,又使您的网站更安全。



还可以考虑从文本框更改 - 您无法控制日期格式或甚至是用户输入的字符 - 改为DateTimePicker或Calender控件,它将返回DateTime值。



尝试简单的方法:

Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead. This will probably both solve the immediate problem and make your site a lot safer.

Also consider changing from a Text box - where you have no control over the date format or even the characters the user enters - to a DateTimePicker or Calender control which will return a DateTime value instead.

Try the simple way:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn1, myColumn2) VALUES (@C1, @C2)", con))
        {
        com.Parameters.AddWithValue("@C1", myValueForColumn1);
        com.Parameters.AddWithValue("@C2", myValueForColumn2);
        com.ExecuteNonQuery();
        }
    }


首先,您必须将文本框值转换为日期。然后,如果它是有效日期,则可以将值添加到数据库中。否则你可以告诉用户输入有效的日期或其他东西(验证)。



例如:

First of all you have to convert the textbox value to a date. Then if it's a valid date, you can add the value to your database. Else you can tell the user to enter a valid date or something (validation).

Example:
DateTime date;

// Try parse TextBox1.Text to a valid DateTime
if(DateTime.TryParse(TextBox1.Text, out date)){

    // Successfully converted :)
   
    // Add it to database
    using (SqlConnection conn = new SqlConnection("ConnectionString"))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("INSERT INTO myTable (myDateColumn) VALUES (@myDateValue)", conn))
        {
            // Add date as a parameter (it's a DateTime, not a string)
            cmd.Parameters.AddWithValue("@myDateValue", date);
            cmd.ExecuteNonQuery();
        }
        conn.close();
    }
}
else{
   // Tell the user to enter a proper date
}





希望它有所帮助......



Hope it helps..


这篇关于如何将asp.net页面的出生日期插入sql server 2008的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆