下午全部!
所以,我试图从我的数据库中获取一个值,这是我的示例代码:
MySqlCommand cmd = new MySqlCommand(" select * from tbluser where userName ='" + txtUser.Text +"'和userPass ='" + txtPass.Text + "'",con);
con.Open(); reader = cmd.ExecuteReader(); int count = 0; while (reader.Read()) { count = count + 1; } if (count == 1) { if (reader.HasRows) { while (reader.Read()) { lblID.Text = reader(0); } } MessageBox.Show("You have successfully logged in!"); homeMain homeMain = new homeMain(); homeMain.Passvalue = txtUser.Text; homeMain.Passvalue = lblID.Text; homeMain.Show(); this.Hide(); }
代码试图实现的是,当我按下LOG-IN时,它会搜索等于txtUser的数据库,然后在lbl.Text上显示id。我在读者(0)下得到了波浪线。什么似乎是问题?
答案 0 :(得分:4)
您的代码存在一些问题。
首先,您应该使用参数化命令来避免可能的SQL注入攻击。其次,您将reader
向前移动两次,因此第二个reader.Read()
将不会返回任何行,假设您的查询返回了1行(就像我们登录用户时一样)。
MySqlCommand cmd = new MySqlCommand("Select Id from tblUser where userName = @username and userPass = @pass", con);
cmd.Parameters.AddWithValue("@username", txtUser.Text);
cmd.Parameters.AddWithValue("@pass", txtPass.Text);
con.Open();
//Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.
object value = cmd.ExecuteScalar();
if (value == null)
{
//login failed
}
else
{
MessageBox.Show("You have successfully logged in!");
homeMain homeMain = new homeMain();
homeMain.Passvalue = txtUser.Text;
homeMain.Passvalue = value.ToString();
homeMain.Show();
this.Hide();
}
答案 1 :(得分:2)
首先注射原因使用参数:
MySqlCommand cmd = new MySqlCommand("Select ID from tbluser where userName =@param1 and userPass =@param2", con);
cmd.Parameters.AddWithValue( "@param1",txtUser.Text )
cmd.Parameters.AddWithValue("@param2" ,txtPass.Text )
其次,一旦你定义了只能获得你可以设置的ID:
...
con.Open();
reader = cmd.ExecuteReader();
using (con)
{
while (reader.Read())
{
lblID.Text=reader[0].ToString();
}
}
答案 2 :(得分:1)
另请尝试:lblID.Text = reader.GetValue(0).ToString();