-1

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;
}
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
user2395000
  • 17
  • 1
  • 7
  • What is a typical value of `email`, and where does it come from? What does "unable to execute" mean? It doesn't compile? It compiles but throws an exception? What is the exception? – Dour High Arch May 21 '13 at 18:30

3 Answers3

3

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
John Woo
  • 258,903
  • 69
  • 498
  • 492
2

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);
Amit Singh
  • 8,039
  • 20
  • 29
1

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);
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61