2014-04-16 89 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谢谢你的队友 –