C# 更新查询和连接属性尚未初始化
我将一个值从form1传递到form2,并将该值用作where条件,但我似乎无法修复它。顺便说一句,我正在更新一张桌子。任何帮助都将不胜感激C# 更新查询和连接属性尚未初始化,c#,sql-server,C#,Sql Server,我将一个值从form1传递到form2,并将该值用作where条件,但我似乎无法修复它。顺便说一句,我正在更新一张桌子。任何帮助都将不胜感激 SqlConnection cn = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=inventory2;Integrated Security=True"); SqlCommand cmd = new SqlCommand();
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");
}
我认为错误消息足够清楚,您必须将连接分配给将要执行的命令。但是在这里,您可能会面临另一个大问题,即SqlInjection。由于这种串联查询文本查询,您必须使用参数化来避免注入,简言之,您的代码如下所示:
string connectioStr = "Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=inventory2;Integrated Security=True";
string querySQL = "Update Items Set Barcode=@Barcode,Productname=@Productname,Prices=@Prices,Quantity=@Quantity 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);
您正在将连接传递给String.Format调用,而不是将其分配给command对象。请使用SqlParameters而不是字符串连接。是的,先生,我将使用参数。我已经添加了“cmd.Connection=cn;”,现在新的错误是“System.Data.SqlClient.SqlException”类型的未处理异常发生在System.Data.dll中。其他信息:附近的语法不正确”(“。在ExecuteOnQuery行上。之所以出现此错误,是因为您的SQL无效:
集合
组周围不应该有括号:更新项目集合条形码=
…谢谢,先生,它已修复!谢谢,先生,我将其更改为参数