我正面临一个问题。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();
}
}
- 您需要在有空格的字段名周围添加引号或括号
-
你应该养成使用参数的习惯
//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注入保护
- 消除添加字符串分隔符的需要
- 消除输入值有引号导致语法错误的风险