窗口表单应用程序如何使用文本框作为sql语句

时间:2018-07-02 07:45:02

标签: c# windows sql-server-2008 combobox

            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();
             } 

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

1 个答案:

答案 0 :(得分:0)

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

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
    }

}

当然,这也应用于插入查询。当您想将值传递给数据库并且不将sql命令与用户输入连接时,请始终使用参数。这会导致解析问题(如果输入包含单引号会怎样?)或更糟糕的是SQL Injection