2013-02-21 71 views
-1

我正在处理一个项目,在该项目中,我必须将表单中的值插入到SQL Server 2008表中。如何将表单中的数据从表单保存到SQL Server 2008中

插入的值之一是许可证编号,但类别列在数据库中为空。我正在使用的代码是:

SqlCommand qry = new SqlCommand(
"INSERT INTO licnscatagory(license_number, catagory) 
VALUES('"+ license_numberTextBox.Text +"','"+ catagoryComboBox.Text +"')", conn; 
qry.ExecuteNonQuery(); 

在数据库license_numbernumeric数据类型和categoryvarchar(50)

回答

1

使用此代码..

SqlCommand qry = new SqlCommand(
"INSERT INTO licnscatagory(license_number,catagory) 
VALUES('"+ license_numberTextBox.Text +"','"+ catagoryComboBox.SelectedItem.Text +"')", conn; 
qry.ExecuteNonQuery(); 
+0

也没有working.any人能告诉我该如何使用“插入”方法被用于ComboBox控件的具体类型,这些值 – user1756571 2013-02-21 13:02:04

2

您的解决方案是容易受到SQL注入黑客。想象一下,用户在你的license_numberTextBox中键入以下内容。

'); DROP TABLE licnscatagory;

除此之外,你的问题是围绕什么是数字的单引号。在ADO.NET中插入如此的正确方法或任何SQL查询就是使用参数。请参阅以下内容:

 SqlCommand qry = new SqlCommand("INSERT INTO licnscatagory (license_number, category) VALUES (@licenseNumber, @category)", conn); 
     qry.Parameters.AddWithValue("licenseNumber", Convert.ToDecimal(license_numberTextBox.Text)); 
     qry.Parameters.AddWithValue("category", catagoryComboBox.Text); 
     qry.ExecuteNonQuery(); 
+0

将决定Text属性是否是用来检索当前选定值的正确的属性。 – 2013-02-21 09:57:18

+0

我对你的回复非常感谢。但是在运行时有一个语法问题。如何解决这个问题。msg是“附近@catagory附近的不正确语法”plz help – user1756571 2013-02-21 10:41:54

+0

我修改了我的回复。我在陈述结尾错过了一个右括号。 – 2013-02-21 11:00:42

3

使用此代码

SqlCommand qry = new SqlCommand(
    "INSERT INTO licnscatagory(license_number,catagory) 
    VALUES('"+ license_numberTextBox.Text +"','"+ catagoryComboBox.SelectedValue+"')", conn; 
    qry.ExecuteNonQuery(); 
相关问题