【问题标题】:SQL Command ErrorSQL 命令错误
【发布时间】:2017-01-05 10:55:07
【问题描述】:

故事是这样的:

我试图将表单中的一些数据插入到我的数据库中,但语法“Vs Say so”有些问题,但我找不到错误并且有人帮助?

MySqlConnection conn = new MySqlConnection("Server=localhost;Database=ltdb;UID=root;Password=1234;port=3306");
try
{
    string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
    conn.Open();
    MySqlCommand cmd = new MySqlCommand(command, conn);
    cmd.ExecuteNonQuery();
    conn.Close();
    MessageBox.Show("Saved !");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

【问题讨论】:

  • 使用参数。您的代码对 SQL 注入开放。
  • 括号必须在发票之后。不是在插入之前
  • 请将VS错误添加到您的描述中。

标签: c# mysql syntax-error


【解决方案1】:

你放错了括号

INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES ('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');

【讨论】:

    【解决方案2】:

    INSERT INTO invoice companyName, ... 缺少左大括号,正确的是

    INSERT INTO invoice(column1, column2, ...) VALUES (@Columns1, @columns2, ...) 
    

    回到第 2 点:你是 open for sql-injection。使用参数化查询。

    【讨论】:

      【解决方案3】:

      改变你的

      string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
      

      string command = "INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES (@name,@rate,@vatno,@tinno,@adline1,@adline2,@city)";
      command.Parameters.AddWithValue("name",txtname.Text);
      command.Parameters.AddWithValue("rate",txtrate.Text);
      ....
      

      *编辑:更多信息,谷歌“c#参数化sql”

      【讨论】:

        猜你喜欢
        • 2017-05-22
        • 2017-10-07
        • 2013-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多