2013-12-08 84 views
2

我在Visual Studio中的窗体窗体中有一个datagrid设置。数据网格从文本框中更新,但我无法获取它来编辑数据库中保存的值。使用DataGrid更新数据库C#

这是我使用的代码:

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); 
     } 
    } 

但我得到的错误:

"You have an error in your SQL syntax; check the manual that corresponds to your SQL server version for the right syntax to use near '"DestinationLocation'"......... "

任何帮助,将不胜感激。

回答

1

你忘了后使用=DestinationLocationName

更改

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 [email protected], [email protected], [email protected], [email protected], 
       [email protected], [email protected], [email protected], [email protected], [email protected]"; 
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(); 
+0

这很好,非常感谢你的帮助。还有一件事,它现在正在更新数据库中的所有条目。我怎样才能让它只更新一行? – user3080562

+0

@ user3080562非常欢迎。请考虑接受为答案。 http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work如果你只更新一行,你应该考虑在你的'UPDATE'查询中使用'WHERE'语句。例如,'... WHERE Name =“blabla”',仅在您的行'Name'为'blabla'的位置更新您的行 –

1

你的SQL需要一个等号DestinationLocation

顺便提一句,您可能不想使用ExecuteReader,因为您没有返回任何值(并且对任何值都没有兴趣。)尝试ExecuteNonQuery

ETA:和SonerGönül完全正确的是需要参数化查询而不是字符串连接!

最后,我假设你不打算在最终版本中硬编码你的连接字符串?

+0

打败我5秒':'' –