-1

这是我尝试使用 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;
}
4

3 回答 3

3

参数化要避免的值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块来正确处理异常
于 2013-05-21T15:25:08.137 回答
2

把你的电子邮件放在一个单独的 qoute 中,因为它是像这样的 varchar..

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);
于 2013-05-21T15:23:26.880 回答
1

select通过添加email单引号来更新您的查询:

   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);
于 2013-05-21T15:24:37.430 回答