我在Visual Studio的Windows窗体中有一个数据网格设置。数据网格从文本框更新,但我无法编辑数据库中保存的值。
这是我正在使用的代码:
private void btnUpdate_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=admin";
string Query = "UPDATE database.taxi SET PickupLocation='" + txtPickupLocation.Text + "',PickupArea='" + comboBxPickupArea.Text + "',PickupTime='" + dateTimePickup.Text + "',DestinationLocation'" + txtDestinationLocation.Text + "',DestinationArea='" + comboBxDestinationArea.Text + "',Name'" + txtCustomerName.Text + "',Address='" + txtCustomerAddress.Text + "',Tour='" + comboBxTour.Text + "',VehicleRegistration='" + txtvehicleregistration.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Entry has been updated");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
但我收到错误:
“您的SQL语法有错误;请查看手册 对应于您的SQL Server版本,以使用正确的语法 靠近'“DestinationLocation'”.........“
任何帮助都将不胜感激。
答案 0 :(得分:1)
在SQL中DestinationLocation
之后需要一个等号。
顺便说一句,您可能不想使用ExecuteReader
,因为您没有返回任何值(并且对任何值都不感兴趣。)请尝试ExecuteNonQuery
。
ETA:SonerGönül绝对正确地需要参数化查询而不是字符串连接!
最后,我假设您不打算在最终版本中对连接字符串进行硬编码?
答案 1 :(得分:1)
您忘记在=
和DestinationLocation
Name
更改您的
DestinationLocation'" + txtDestinationLocation.Text
和
Name'" + txtCustomerName.Text + "'
到
DestinationLocation = '" + txtDestinationLocation.Text
和
Name = '" + txtCustomerName.Text + "'
但请不要在SQL查询中使用字符串连接。请改用parameterized queries
。这种字符串连接对SQL Injection
攻击开放。
此外,您不需要使用ExecuteReader
,因为您的查询不会返回任何内容。请改用ExecuteNonQuery
。
作为完整代码;
string Query = "UPDATE database.taxi SET PickupLocation=@PickupLocation, PickupArea=@PickupArea, PickupTime=@PickupTime, DestinationLocation=@DestinationLocation,
DestinationArea=@DestinationArea, Name=@Name, Address@Address, Tour=@Tour, VehicleRegistration=@VehicleRegistration";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
cmdDataBase.Parameters.AddWithValue("@PickupLocation", txtPickupLocation.Text);
cmdDataBase.Parameters.AddWithValue("@PickupArea", comboBxPickupArea.Text);
....
....
cmdDataBase.ExecuteNonQuery();