简体   繁体   中英

Unable to execute cmd.ExecuteReader()

Here is the code where i'm trying to retrieve user name using 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;
}

parameterized the value to avoid from SQL Injection

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

Try this code snippet:

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

For proper coding

  • use using statement for proper object disposal
  • use try-catch block to properly handle exception

Put you emailin sigle qoute because it is varchar like this..

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

But this may cause SQL Injection...so use this...

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

Update your select query like this with adding email in single quote:

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

or you can use parametrized query like this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM