C# 在C中从数据库获取值
下午好 因此,我试图从数据库中获取一个值,这是我的示例代码: MySqlCommand cmd=new MySqlCommandSelect*from tbluser where userName='+txtser.Text+'和userPass='+txtPass.Text+ ",con,C# 在C中从数据库获取值,c#,mysql,C#,Mysql,下午好 因此,我试图从数据库中获取一个值,这是我的示例代码: MySqlCommand cmd=new MySqlCommandSelect*from tbluser where userName='+txtser.Text+'和userPass='+txtPass.Text+ ",con, con.Open(); reader = cmd.ExecuteReader(); int count = 0
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。我在reader0下面看到了几条弯弯曲曲的线。有什么问题吗?或者尝试一下:lblID.Text=reader.GetValue0.ToString 第一个注射原因使用参数:
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();
}
}
您的代码有一些问题 首先,您应该使用参数化命令来避免可能的SQL注入攻击。第二,您向前移动了两次读卡器,所以第二个读卡器.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();
}
使用[]访问arrayIt的读卡器[0]的项目不是我已经尝试过了,先生,但是我得到了一个错误:“hotelSys.logIn.reader”是一个“字段”,但像“方法”一样使用,不起作用。读卡器[0]将是一个对象,而.Text需要字符串。我也尝试过,但没有成功。这是我的错误,'hotelSys.logIn.reader'是一个'field',但像'method'一样使用。此外,ToString将在对象中打印出默认实现。您需要将其强制转换为字符串这是我更改代码时出现的新错误:“object”不包含“toString”的定义,并且找不到接受“object”类型第一个参数的扩展方法“toString”?是否缺少using指令或程序集引用?嗯,当然。我试试看。事实上,我是C:D的新手