无法执行cmd.ExecuteReader()

本文关键字:ExecuteReader cmd 执行 | 更新日期: 2023-09-27 18:14:33

这是我试图使用emailid检索用户名的代码。

string query="select name from userdetails where emailid=" + email + ";" ;
connection.Open();
MySqlCommand cmd = new MySqlCommand(query,connection);
MySqlDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{ 
    uname = (string)rd["emailid"];  
    return uname;
}

无法执行cmd.ExecuteReader()

参数化避免SQL Injection的值

string query="select name from userdetails where emailid=@email" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("@email", email);

试试下面的代码片段:

string connStr = "connection string here";
string sqlStatement = "select name from userdetails where emailid=@email";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
    using(MySqlCommand comm = new MySqlCommand())
    {
        comm.Connection = conn;
        comm.CommandText = sqlStatement;
        comm.CommandType = CommandType.Text;
        comm.Parameters.AddWithValue("@email", email);
        try
        {
            conn.Open();
            MySqlDataReader rd = cmd.ExecuteReader();
            // other codes
        }
        catch(SqlException e)
        {
            // do something with the exception
            // do not hide it
            // e.Message.ToString()
        }
    }
}

正确编码

  • 使用using语句进行正确的对象处理
  • 使用try-catch块正确处理异常

给你发单引号,因为它是这样的。

string query="select name from userdetails where emailid='" + email + "';" ;

但这可能会导致SQL注入…所以用这个…

 string query="select name from userdetails where emailid=@email;" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("@email",email);

像这样在单引号中添加email来更新您的select查询:

   string query = "select name from userdetails where emailid='" + email +"';";

或您可以像这样使用参数化查询:

string query="select name from userdetails where emailid=@email" ;
MySqlCommand cmd = new MySqlCommand(query,connection);
cmd.Parameters.AddWithValue("@email", email);