简体   繁体   English

C#检查值是否从数据库返回

[英]C# Check if value is returned from database

 SqlCeConnection sqlCnn = new SqlCeConnection("Data Source=" + Application.StartupPath + "\\mainDB.sdf");
 SqlCeCommand sqlCmd = new SqlCeCommand("SELECT * FROM Accounts WHERE (username = @user AND password = @pass)", sqlCnn);
 sqlCmd.Parameters.Add("@user", textBox1.Text);
 sqlCmd.Parameters.Add("@pass", textBox2.Text);
 sqlCnn.Open();
 SqlCeDataReader reader = sqlCmd.ExecuteReader();
 while (reader.Read())
 {
    // Some code ...
 }

I have this code that reads some values from a database but I want to check if any value is returned from the database. 我有这段代码从数据库读取一些值,但是我想检查是否从数据库返回了任何值。 I want to check if the username and password from the database is equal to textBox1 and textBox2 and if not, return a failure message. 我想检查数据库中的usernamepassword是否等于textBox1textBox2 ,如果不相同,则返回失败消息。

Simply use the code like this: 只需使用如下代码:

if(reader.Read()){
   //your code
}else {
  //Show message notifying failure
}
//remember to close your reader
reader.Close(); //or use using statement for convenience.

However DataReader is used mainly for reading a set of data (just 1 record is a little overkill). 但是, DataReader主要用于读取一组数据(仅一条记录就有点过头了)。 You can try modifying your query a little such as by using If Exists(...)... and use ExecuteScalar() to get the return result. 您可以尝试稍微修改查询,例如使用If Exists(...)...然后使用ExecuteScalar()获得返回结果。 If it's not null then it's OK. 如果不为null则可以。

//the modified query
If Exists(SELECT * FROM Accounts WHERE (username = @user AND password = @pass))
SELECT 1 ELSE SELECT 0

var r = sqlCmd.ExecuteScalar();
if(r == null || (int)r == 0){
  //failure...
}

I would "select count(*) from ..." 我会“从...中选择count(*)”

Then do ExecuteScalar() instead. 然后改为执行ExecuteScalar()。 This will return an int. 这将返回一个int值。

SqlCeConnection sqlCnn = new SqlCeConnection("Data Source=" + Application.StartupPath + "\\mainDB.sdf");
 SqlCeCommand sqlCmd = new SqlCeCommand("SELECT count(*) FROM Accounts WHERE (username = @user AND password = @pass)", sqlCnn);
 sqlCmd.Parameters.Add("@user", textBox1.Text);
 sqlCmd.Parameters.Add("@pass", textBox2.Text);
 sqlCnn.Open();
 int recordCount = (int)sqlCmd.ExecuteScalar();

if (recordCount > 0)
{
//dostuff
}

Check if your Datateader has rows with reader.HasRows. 检查您的Datateader是否包含具有reader.HasRows的行。

See this SO post How to check if SQLDataReader has no rows for more info. 请参阅此SO文章如何检查SQLDataReader是否没有行以获取更多信息。

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

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