更新查询和连接属性尚未初始化

时间:2017-01-04 16:44:42

标签: 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();
    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");
        }

1 个答案:

答案 0 :(得分:0)

我认为错误消息足够清楚,您必须将连接分配给将要执行的命令。但是在这里你可能面临另一个大问题,即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);