2013-12-08 81 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秒':'' –