首页 > 解决方案 > 为什么在尝试更新数据库时出现语法错误?

问题描述

我一直试图环顾四周并解决这个问题,并且我已经尝试了几个小时,所以我决定我会问其他人。我得到一个

'UPDATE 语句中的语法错误。'

单击保存按钮时。

这是我的代码:

OleDbCommand command = new OleDbCommand();
command.Connection = connection;

string query = "update Profiles set [PROFILE NAME]='" + textBox1.Text + "', [LOGIN EMAIL]='" + textBox2.Text + "', [PASSWORD]='" + textBox3.Text + "', [FULL NAME]='" + textBox4.Text + "', [CARD NUMBER]='" + textBox5.Text + "', [EXP MONTH]='" + comboBox1.Text + "', [EXP YEAR]='" + comboBox2.Text + "', CVV='" + textBox6.Text + "', where ID=" + textBox7.Text + "";
command.CommandText = query;
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Profile Saved");
RefreshDBConnection();

更新代码:

ConnectToDataBase();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;

//string query = "update Profiles set [PROFILE NAME]='" + textBox1.Text + "', [LOGIN EMAIL]='" + textBox2.Text + "', [PASSWORD]='" + textBox3.Text + "', [FULL NAME]='" + textBox4.Text + "', [CARD NUMBER]='" + textBox5.Text + "', [EXP MONTH]='" + comboBox1.Text + "', [EXP YEAR]='" + comboBox2.Text + "', CVV='" + textBox6.Text + "' where  ID='" + Convert.ToInt32(textBox7.Text) + "'";
string query = "update Profiles set [PROFILE NAME]= @Profile, [LOGIN EMAIL]= @Email, [PASSWORD]= @Pass, [FULL NAME]= @Name, [CARD NUMBER]= @Card, [EXP MONTH]= @EXPM, [EXP YEAR]= @EXPY, CVV= @CVV where ID = '" +textBox7.Text+ "'";
command.Parameters.AddWithValue("@Profile", textBox1.Text);
command.Parameters.AddWithValue("@Email", textBox2.Text);
command.Parameters.AddWithValue("@Pass", textBox3.Text);
command.Parameters.AddWithValue("@Name", textBox4.Text);
command.Parameters.AddWithValue("@Card", Convert.ToInt32(textBox5.Text));
command.Parameters.AddWithValue("@EXPM", Convert.ToInt32(comboBox1.Text));
command.Parameters.AddWithValue("@EXPY", Convert.ToInt32(comboBox2.Text));
command.Parameters.AddWithValue("@CVV", Convert.ToInt32(textBox6.Text));
command.CommandText = query;
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Profile Saved");
RefreshDBConnection();
this.Close();

标签: c#.netms-accessado.net

解决方案


你的语句,前多了一个逗号:Where

CVV='" + textBox6.Text + "', where 

只需将其删除。如果它的类型是整数,你应该将你的转换textBox7.Text为 int,ID= '" + Convert.ToInt32(textBox7.Text) + "'(不要忘记用单引号括起来)。此外,您应该始终使用参数化查询来避免SQL 注入。像这样的东西:

string query = "update Profiles set [PROFILE NAME]= @Profile,... where ID = @Id";
command.Parameters.AddWithValue("@Profile", textBox1.Text);
command.Parameters.AddWithValue("@Id", textBox7.Text);//Or Convert.ToInt32(textBox7.Text)

虽然直接指定类型并使用Value属性比AddWithValue

command.Parameters.Add("@Profile", SqlDbType.VarChar).Value = textBox1.Text;
command.Parameters.Add("@Id", SqlDbType.Int).Value = Convert.ToInt32(textBox7.Text);

当然,建议using始终使用语句。


推荐阅读