繁体   English   中英

在C#中从数据库获取值

[英]Getting a value from database in C#

下午都好!

因此,我正在尝试从数据库中获取一个值,这是我的示例代码:

MySqlCommand cmd = new MySqlCommand(“从tbluser中选择*,其中userName ='” + txtUser.Text +“'和userPass ='” + txtPass.Text +“',co​​n));

  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。 我在reader(0)下有弯曲的线条。 似乎是什么问题?

您的代码存在一些问题。

首先,您应该使用参数化的命令来避免可能的SQL Injection攻击。 其次,您将reader向前移动了两次,因此第二个reader.Read()不会返回任何行, 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();
}

首先出于注射原因使用参数:

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

或者尝试以下操作: lblID.Text = reader.GetValue(0).ToString();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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