2014-02-28 19 views
1

我已将由sql server创建的本地数据库与Visual Studio(C#)中的项目连接起来。现在我希望将用户输入到我的数据库中的文本字段中给出的数据。这是我曾试图做的事通过事件处理程序将值插入表

private void Button_AddCustomer_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      //SqlConnection objsqlconn = new SqlConnection(conn); 
      SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" + 
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True"); 
      myConnection.Open(); 
      SqlCommand objcmd = new SqlCommand("INSERT INTO 
Customer(PhoneNumber,MobileNumber,Address) VALUES (a, b, c)", myConnection); 
      objcmd.ExecuteNonQuery(); 
     } 
     catch(SqlException ex) 
     { 
       MessageBox.Show(ex.ToString()); 
     } 
    } 

它抛出一个异常说invalid column name a,invalid column name b,invalid column name c。什么问题,以及如何使用插入查询从用户输入到我的数据库?我正在开发Visual Studio C#,并使用ms sql创建本地数据库。

回答

0

更换

VALUES (a, b, c) 

VALUES (' + textBox1.value + (other text area) + ')' 

查询之前,请检查输入反正!

SqlCommand objcmd = new SqlCommand("INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('" + PhoneNumber.Text + "', '" + MobileNumber.Text + "', '" + Address.Text + "')", myConnection); 
+0

的SqlCommand objcmd =新的SqlCommand( “INSERT INTO顾客(******中国,移动电话号码,地址)VALUES( 'PhoneNumber.Text + MobileNumber.Text + Address.Text')”,MyConnection的); – user3085866

+0

这就是我所做的,仍然抛出exxception – user3085866

+0

在值之间添加“,”+值 –

0

你需要单引号内的字符串类型。

试试这个:

INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('a','b','c') 

建议:您的查询是开放的sql injection attacks请使用Parameterised queries避免它们。

试试这个:使用参数化查询

private void Button_AddCustomer_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      //SqlConnection objsqlconn = new SqlConnection(conn); 
      SqlConnection myConnection = new SqlConnection(
      "Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;" 
              + "Integrated Security=True"); 
      myConnection.Open(); 
      SqlCommand objcmd = new SqlCommand("INSERT INTO 
        Customer(PhoneNumber,MobileNumber,Address) VALUES 
        (@phonenumber,@mobilenumber,@address)", myConnection); 
      objcmd.Parameters.AddWithValue("@phonenumber",TextBox1.Text); 
      objcmd.Parameters.AddWithValue("@mobilenumber",TextBox2.Text); 
      objcmd.Parameters.AddWithValue("@address",TextBox3.Text); 
      objcmd.ExecuteNonQuery(); 
     } 
     catch(SqlException ex) 
     { 
       MessageBox.Show(ex.ToString()); 
     } 
    } 
+0

后,我这样做INSERT INTO客户(PhoneNu mber,MobileNumber,Address)VALUES('a','b','c')它将b和c作为字符串添加到我的数据库中 – user3085866