c# - Else 语句无法在 while 循环内工作
问题描述
下面是我使用 MySqlDataReader 连接到数据库的代码。现在 if 语句工作正常,但 else 语句没有。当我在 VS 中使用调试功能时,它一直跳过 else 语句并跳转到 reader.Close();。任何的想法。谢谢
private void db()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
MySqlConnection connection = new MySqlConnection(constr);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM user Where user_id ='" + Userid.Text + "'" + "And password='" + Password.Text + "'";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
Label1.Text = reader["user_id"].ToString();
}
else
{
Label1.Text = "nodata";
}
reader.Close();
}
}
解决方案
首先:不要使用字符串连接来构建查询,而是使用参数化查询!
至于你的问题:我假设这个查询只会返回 1 或 0 行,所以你不需要循环,只需检查
if (reader.Read()) {
//...
}
与列索引一起使用SELECT *
可能很危险,因为您可能不知道返回的“第一”列是什么。我建议在查询中命名您想要的列
SELECT user_id, user_name ... FROM ...
What is the value of the first column returned? I assume, it's the user_id
. Thus, this can never fulfill the condition IsDBNull(0)
because user_id
is your matching criterion in the WHERE
clause. If your WHERE
clause does not match any record in the table, reader.Read()
will already fail, so you'll never get to your else branch.
Furthermore, I would suggest a using
clause, which will dispose the reader automatically, so you don't have to care about closing it.
command.CommandText = "SELECT user_id, foo, bar from user where user_id = @userid and password = @password";
command.Parameters.AddWithValue("@user_id", UserId.Text);
command.Parameters.AddWithValue("@password", Passowrd.Text);
using (MySqlDataReader reader = command.ExecuteReader()) {
if (reader.Read()) {
Label1.Text = reader["user_id"].ToString();
} else {
Label1.Text ="nodata";
}
}
推荐阅读
- regex - 正则表达式:捕获两个字符串之间的所有内容,除了那些字符串
- c# - 在 StackPanel 中按比例拉伸子项
- python - 使用protobuf编译时是否可以循环,将.proto文件转换为.py文件?
- c - 如何在 C 中的矩阵(二维数组)内声明双精度数?
- javascript - 如何从描述性对象动态生成类?
- function - Racket 中的“过程”和“功能”是同义词吗?
- git - 是否`
/ 这个 `git checkout` 命令中的` 代表远程分支还是远程跟踪分支? - python - What is the Keras 2.0 equivalent of `similarity = keras.layers.merge([target, context], mode='cos', dot_axes=0)`
- tensorflow - TensorFlow 损失的初始跳跃
- javascript - 如何创建精灵图像按钮并将其添加到 3D 画布?