我在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
和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();
在SQL中DestinationLocation
之后需要一个等号。
顺便说一句,您可能不想使用ExecuteReader
,因为您不会返回任何值(并且对任何值都不感兴趣)。请尝试ExecuteNonQuery
。
ETA:Soner Gönül关于参数化查询而不是字符串串联的需求是绝对正确的!
最后,我假设您不会在最终版本中对连接字符串进行硬编码?