c# - C#从数据库中获取值

标签 c# mysql

大家下午好!

所以,我试图从我的数据库中获取一个值,这是我的示例代码:

MySqlCommand cmd = new MySqlCommand("Select * from tbluser where userName ='" + txtUser.Text + "' and 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。我在 reader(0) 下有波浪线。似乎是什么问题?

最佳答案

您的代码存在一些问题。

首先,您应该使用参数化命令来避免可能的 SQL 注入(inject)攻击。其次,您将 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();
}

关于c# - C#从数据库中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23883632/

相关文章:

c# - 使用箭头键控制菜单并输入

c# - 使用 NUnit 按顺序运行 TestFixtures

php - 如何在WordPress中使用更新和删除查询

MySQL LoopBack 中的多对多关系

MYSQL只统计编号为1的学生

mysql - 如何对具有更多未读消息的用户进行排序,使其首先出现在mysql结果中

忽略过程中的 MySQL WHERE 条件

c# - AutoMapper:如何获取目标属性的名称

c# - 将数据绑定(bind)到 busyindicator 中的数据模板的问题

c# - WinForms AcceptButton 不工作?