2014-04-16 88 views
0

我試圖用一個文本框的文本在mysql數據庫中選擇一行。 但是,當我使用下面的代碼時,我得到一個錯誤。C#的Mysql文本框文本選擇

 MySqlCommand command = connection.CreateCommand(); //we create a command 
     command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ; //in commandtext, we write the Query 
     MySqlDataReader reader = command.ExecuteReader(); //execute the SELECT command, which returns the data into the reader 

     while (reader.Read()) //while there is data to read 
     { 
      MessageBox.Show(reader["info"].ToString()); 
     } 

它工作正常,用字母,但是當我嘗試使用問號或類似的東西,我得到以下錯誤:‘?’

「參數必須定義。「在這種情況下

+1

你可以張貼例外? –

+0

MySql.Data.MySqlClient.MySqlException未處理 HResult = -2147467259 消息=參數'?'必須定義。 Source = MySql.Data ErrorCode = -2147467259 – user3540727

+0

由於目前的情況,您的代碼很容易受到SQL注入攻擊。我強烈建議你考慮使用下面答案中給出的參數。 – mcy

回答

0

您更好地使用參數

command.CommandText = "SELECT * FROM info where [email protected]"; 

,那麼你需要設置參數值

command.Parameters.AddWithValue(@id, textBox1.Text); 

全碼:

string queryString="SELECT * FROM info where [email protected]"; 
    using (MySqlConnection connection = new MySqlConnection(connectionString)) 
    using (MySqlCommand command = new MySqlCommand(queryString, connection)) 
    { 
     connection.Open(); 
     command.Parameters.AddWithValue("@id", textBox1.Text); 
     using (MySqlDataReader reader = command.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       // do something ... 
      } 
     } 
    } 

更新:

變化您的參數值設置線如下

command.Parameters.AddWithValue("@id", textBox1.Text); 
+0

我似乎無法得到它的工作如何將我的代碼添加到我的現有?這是我現在的代碼:http://pastebin.com/raw.php?i=k87zcCn9 – user3540727

+0

@ user3540727你需要設置參數值爲'command.Parameters.AddWithValue(「@ id」,textBox1.Text );' – Damith

+0

當我這樣做時,沒有任何東西從數據庫中返回。 – user3540727

1

代替

command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ; 

使用此

command.CommandText = "SELECT * FROM info where [email protected]"; 
command.Parameters.AddWithValue("@id",textBox1.Text); 
+1

始終是最佳實踐。 – TheGeekZn

+0

@NewAmbition謝謝你的隊友 –