以下是我尝试使用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;
}
答案 0 :(得分: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
块来正确处理异常答案 1 :(得分:2)
将你的电子邮件发送给sigle 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);
答案 2 :(得分: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);