语法错误near,debit

本文关键字:debit near 错误 语法 | 更新日期: 2023-09-27 18:05:31

我正面临一个问题。DEBIT

附近的语法不正确。
private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection(global::databaseform.Properties.Settings.Default.Database2ConnectionString);
        try
        {
            //string sql = "INSERT INTO student(Id,name) values (" + textBox1.Text + ",'" + textBox2.Text + "')";
            //JOURNAL
            string sql = "INSERT INTO journal(user_Id, DATE, MEMO, ACCOUNT DEBIT, ACCOUNT CREDIT, AMOUNT DEBIT, AMOUNT CREDIT) values (" + user_id.Text + "," + date.Text + ",'" + memo.Text + "','" + debit.Text + "','" + credit.Text + "'," + debit_am.Text + "," + credit_am.Text + ")";
            SqlCommand eesql = new SqlCommand(sql, cn);
            cn.Open();
            eesql.ExecuteNonQuery();
            MessageBox.Show("Add new record  done ||", " Message ", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.journalTableAdapter.Fill(this.database2DataSet.journal);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, " ERROR ", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            cn.Close();
        }
    }

语法错误near,debit

  1. 您需要在有空格的字段名周围添加引号或括号
  2. 你应该养成使用参数的习惯

    //JOURNAL
    string sql = "INSERT INTO journal(user_Id, DATE, MEMO, [ACCOUNT DEBIT], [ACCOUNT CREDIT], [AMOUNT DEBIT], [AMOUNT CREDIT])" + 
                 " values " + 
                 " (@userid, @date, @memo, @debit, @credit, @debit_am, @credit_am)";
    SqlCommand eesql = new SqlCommand(sql, cn);
    eesql.Parameters.AddWithValue("@userid", user_id.Text);
    eesql.Parameters.AddWithValue("@date", date.Text);
    ..etc.
    
使用参数的三个主要原因是:
    SQL注入保护
  1. 消除添加字符串分隔符的需要
  2. 消除输入值有引号导致语法错误的风险