2017-01-04 203 views
0

我将一个值从form1传递给form2,并将该值用作where条件,但是我似乎无法修复它。我正在更新一张桌子btw。任何帮助将不胜感激。更新查询和连接属性尚未初始化

SqlConnection cn = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=inventory2;Integrated Security=True"); 
    SqlCommand cmd = new SqlCommand(); 
    SqlDataAdapter adptr = new SqlDataAdapter(); 
    DataSet dt = new DataSet(); 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if (this.Text == "EDIT") 
     {   
      cmd.CommandText = string.Format("Update Items Set (Barcode='" + txtcode.Text + "' ,Productname= '" + txtitemname.Text + "',Prices= '" + txtPrices.Text + "' ,Quantity= '" + txtquantity.Text + "' ,Brand= '" + txtbrand.Text + "',Expiry= '" + txtexpiry.Text + "',Description='" + txtdescription.Text + "' ,Critical= '" + txtcritical.Text + "' where Barcode = '" + txtTry.Text + "')", cn);   
      cmd.ExecuteNonQuery(); 
      MessageBox.Show("Records Updated!"); 
      txtcode.Text = ""; 
      txtitemname.Text = ""; 
      txtPrices.Text = ""; 
      txtquantity.Text = ""; 
      txtbrand.Text = ""; 
      txtexpiry.Text = ""; 
      txtdescription.Text = ""; 
      txtcritical.Text = ""; 
     } 
     else 
     { 
      MessageBox.Show("Invalid"); 
     } 
+0

您将连接传递给String.Format调用,而不是将它分配给命令对象。 **请**使用SqlParameters而不是字符串连接。 – stuartd

+0

是的,先生使用参数。我已经添加了“cmd.Connection = cn;”现在新的错误是“System.Data.SqlClient.SqlException发生在System.Data.dll 类型'的未处理的异常'其他信息:在执行查询行上'('。''附近的语法不正确 – FutureDev

+0

您得到该错误,因为你的SQL是无效的:'set'组不应该有括号:'更新项目设置条形码='... – stuartd

回答

0

我认为错误信息已经足够清楚了,您必须将连接分配给将要执行的命令。但在这里,你可能会面临的另一大问题,即SQL注入攻击,因为这种级联查询文本查询,您必须使用参数来避免注射,总之你的代码将是如下所示:

string connectioStr = "Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=inventory2;Integrated Security=True"; 
string querySQL = "Update Items Set [email protected],[email protected],[email protected],[email protected] where Barcode = @condition"; 
// add more columns as you needed in the set 
using (SqlConnection conSQL = new SqlConnection(connectioStr)) 
{ 
    using (SqlCommand cmdSQL = new SqlCommand()) 
    { 
     cmdSQL.Connection = conSQL; 
     cmdSQL.CommandText = querySQL; 
     cmdSQL.Parameters.Add("@Barcode", SqlDbType.VarChar).Value = txtcode.Text; 
     cmdSQL.Parameters.Add("@Productname", SqlDbType.VarChar).Value = txtitemname.Text; 
     cmdSQL.Parameters.Add("@Prices", SqlDbType.VarChar).Value = txtPrices.Text; 
     cmdSQL.Parameters.Add("@Quantity", SqlDbType.VarChar).Value = txtquantity.Text; 
     cmdSQL.Parameters.Add("@condition", SqlDbType.VarChar).Value = txtcode.Text; 
     // Add all parameters specified in the query 
     // use appropriate datatypes as per the type of columns 
    } 
} 

您可以在初始化命令时指定命令的连接和查询;在这种情况下,命令初始化将如下所示:

SqlCommand cmdSQL = new SqlCommand(querySQL,conSQL); 
+0

谢谢先生虐待它改变参数 – FutureDev

相关问题