我选择时语法不正确,第一个名称附近的错误

时间:2017-12-11 11:26:10

标签: c# sql visual-studio

我有一个错误的问题。但我有另一种形式的命令,不要给我错误。

这是代码:

string select = "select CONCAT(nume,' ',prenume) from echipa where email=@EMAIL";

            cmd.Connection = con;


            if (bunifuCheckbox1.Checked == true)
            {
                con.Open();
                cmd.CommandText = "Insert into clienti_fizici(nume,prenume,email,telefon,adresa,data_nasterii,data_ora,CNP,sex,judetprovenienta,temperamentclient,provenientaclient,descriere,numeagent)values('"
+ bunifuMaterialTextbox1.Text + "','" + bunifuMaterialTextbox2.Text + "','" + bunifuMaterialTextbox4.Text + "','" + bunifuMaterialTextbox8.Text + "','" + bunifuMaterialTextbox3.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss") + "','" + bunifuDatepicker1.Value.Date + "','" + bunifuMaterialTextbox11.Text + "','" + gender + "','" + bunifuMaterialTextbox12.Text + "','" + bunifuDropdown1.selectedValue + "','" + bunifuDropdown2.selectedValue
+ "','" + richTextBox1.Text + "','" + select + "')";
                cmd.Parameters.AddWithValue("@EMAIL", loginform.Email);
                MessageBox.Show("Datele au fost introduse in baza de date !");
                cmd.ExecuteNonQuery();
                con.Close();
            }

,错误将来自该选择。 enter image description here

1 个答案:

答案 0 :(得分:0)

首先,您必须永远不要将字符串与用户输入连接以创建SQL语句。相反,始终参数化您的SQL语句。否则你会冒SQL injection次攻击。

其次,你不能在select条款中使用values 您可以执行的操作为select语句添加参数或硬编码值。

第三,SqlConnectionSqlCommand都实现IDisposable接口,应该用作using块内的局部变量。

更好的代码看起来像这样:

if (bunifuCheckbox1.Checked == true)
{

    string sql = "Insert into clienti_fizici(nume, prenume, email, telefon, adresa, data_nasterii, data_ora, CNP, sex, judetprovenienta, temperamentclient, provenientaclient, descriere, numeagent) " + 
                 "SELECT @nume, @prenume, @email, @telefon, @adresa, @data_nasterii, @data_ora, @CNP, @sex, @judetprovenienta, @temperamentclient, @provenientaclient, @descriere, CONCAT(nume,' ',prenume) " + 
                 "FROM echipa where email = @EMAIL";

    // Note: SqlConnection should be opened for the shortest time possible - the using statement close and dispose it when done.
    using(var con = new SqlConnection(connectionString))
    {
        // SqlCommand is also an IDisposable and should be disposed when done.
        using(var cmd = new SqlCommand(sql, con)
        {
        cmd.Parameters.Add("@nume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox1.Text;
        cmd.Parameters.Add("@prenume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox2.Text;
        //... Add the rest of the parameters here...
        cmd.Parameters.Add("@EMAIL", SqlDbType.NVarChar).Value = loginform.Email;
        // Why is this here? MessageBox.Show("Datele au fost introduse in baza de date !");
        con.Open();
        cmd.ExecuteNonQuery();
        }
    }
}