gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:10:16 25 4
gpt4 key购买 nike

大家下午好!

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com