C# 窗口窗体应用程序如何将textbox用作sql语句

C# 窗口窗体应用程序如何将textbox用作sql语句,c#,windows,sql-server-2008,combobox,C#,Windows,Sql Server 2008,Combobox,如何将文本框用作SQL语句中的值。我尝试将“1508-527-00”更改为“+textbox3.text+”或将值更改为“+temp+”,但出现了一个错误,表中的数据类型为varchar。使用用户键入的值编写查询的正确方法如下 temp = textBox3.Text; query6 = "SELECT DISTINCT Weight_Box FROM MO_spec WHERE PC = '1508-527-00' ";

如何将文本框用作SQL语句中的值。我尝试将“1508-527-00”更改为“+textbox3.text+”或将值更改为“+temp+”,但出现了一个错误,表中的数据类型为varchar。

使用用户键入的值编写查询的正确方法如下

            temp = textBox3.Text;
            query6 = "SELECT DISTINCT Weight_Box FROM MO_spec WHERE PC = '1508-527-00' ";
            SqlCommand cmd6 = new SqlCommand(query6, con5);
            SqlDataReader dr1 = cmd6.ExecuteReader();
             if (dr1.Read())
             {    w1 = (float)dr1["Weight_Box"];
                 float a1 = (float)Convert.ToDouble(textBox5.Text);
                 bool valid1 = float.TryParse(textBox5.Text.ToString(), out a1);
                 nw1 = w1 * a1;
                 query13 = "insert into intern_planuser(DocCode,DocDate,VenderName,Licenseplate,DriverName,OrderItem,ProductCode,WeightPerUnit,Amount,NetWeight) values('" + label17.Text + "','" + label3.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + comboBox3.Text + "','" + textBox1.Text + "','" + textBox3.Text + "',w1,a1,nw1";
                 SqlCommand cmd13 = new SqlCommand(query13, con5);
                 cmd13.Connection.Open();
                 cmd13.ExecuteNonQuery();
                 cmd13.Connection.Close();
                 MessageBox.Show("saved");
             }
             else
             {
                 MessageBox.Show("Please enter PC in the corect form OR cannot retrive data from database");
                 textBox3.Focus();
             } 

当然,这也应该用于insert查询。要将值传递到数据库时,请始终使用参数,并且不要将sql命令与用户输入连接起来。这会导致解析问题(如果输入包含一个引号怎么办?)或者更糟糕的是使用SQL参数……在dr1之后,我可以问更多关于这方面的问题吗?如何将值带到变量进行计算
bool valid1 = false;
query6 = "SELECT DISTINCT Weight_Box FROM MO_spec WHERE PC = @pc";
using(SqlCommand cmd6 = new SqlCommand(query6, con5)))
{
    cmd6.Parameters.Add("@pc", SqlDbType.VarChar).Value = textBox1.Text;
    using(SqlDataReader dr1 = cmd6.ExecuteReader())
    {
         if(dr1.Read())
         {
             w1 = Convert.ToSingle(dr1["Weight_Box"]);
             valid1 = float.TryParse(textBox5.Text, out a1);
         }
    } 
    // Closing the reader here allows the following query without
    // MultipleActiveRecordset active in your connectionstring
    if(valid1)
    {
         // the remainder of your code goes here.
         // Inside proper using blocks and with the correct parameters
    }

}