C# 检查数据表是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12358950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:59:07  来源:igfitidea点击:

Checking if a datatable is null

c#sql

提问by Tony

The following code is what I've been using to retrieve user information from a sql database.

以下代码是我用来从 sql 数据库中检索用户信息的代码。

            string userName = LoginUser.UserName;
            string password = LoginUser.Password;
            string comm = "SELECT Username,Password,Clientname,Role FROM Users WHERE Username = '" + userName + "';";
            bool rememberUserName = LoginUser.RememberMeSet;

            SqlConnection conn = new SqlConnection(connstring);
            conn.Open();

            SqlCommand command = new SqlCommand(comm, conn);
            SqlDataAdapter da = new SqlDataAdapter(command);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataRow dr = dt.NewRow();
            if (dt != null)
            {
                //logic
            }

However, (dt != null) does not return false when there is no entry in the database with the username equal to LoginUser.Username. Is there a different way to check whether or not the sqlcommand is successful?

但是,当数据库中没有用户名等于 LoginUser.Username 的条目时,(dt != null) 不会返回 false。是否有不同的方法来检查 sqlcommand 是否成功?

采纳答案by driis

You will get an empty DataTableif no records match, so you can check on the number of records returned:

DataTable如果没有记录匹配,您将得到一个空值,因此您可以检查返回的记录数:

if (dt.Rows.Count > 0)

And, slightly off topic, please read the comments below your question, then Google the terms SQL Injection and Parameterized SQL statements. Try starting with this.

而且,稍微偏离主题,请阅读您问题下方的评论,然后在 Google 上搜索术语 SQL 注入和参数化 SQL 语句。尝试从这个开始。

回答by Justin Niessner

Why not just change the statement a bit to see if the DataTable is either null or has no rows:

为什么不稍微更改语句以查看 DataTable 是否为空或没有行:

if(dt != null && dt.Rows.Count > 0)

Also, on a side note, you should look into Parameterized Queries as well rather than building your SQL dynamically. It will reduce the number of attack vectors for attackers trying to compromise your application.

此外,附带说明一下,您还应该查看参数化查询,而不是动态构建 SQL。它将减少试图破坏您的应用程序的攻击者的攻击向量数量。

回答by Michael Domashchenko

It seems to me using a DataTable and SqlDataAdapter is a little bit too heavy for the task.

在我看来,使用 DataTable 和 SqlDataAdapter 对任务来说有点太重了。

You can just use a DataReader here:

您可以在此处使用 DataReader:

        SqlCommand command = new SqlCommand(comm, conn);
        using (var reader = command.ExecuteQuery()) 
        {
            if (reader.Read())
            {
                //logic
                var userName = reader.GetString(0);
                var password = reader.GetString(1);
                // etc
            }
        }

回答by Arun Agarwal

It will be better if you use try catchfor checking whether the table is empty or not , just handle the IndexOutOfRangeExceptionexception.

如果try catch用于检查表是否为空会更好,只需处理IndexOutOfRangeException异常即可。

Use the following logic:

使用以下逻辑:

try
{
   //dataTable operations
}
catch(IndexOutOfRangeException)
{
}

For me its working.

对我来说它的工作。

回答by BinaryTie

For DataSetyou can check like this:

因为DataSet你可以这样检查:

if (ds.Tables[0].Rows.Count > 0)

回答by YeinCM-Qva

I know this question IS OLD and the answers helped at the moment it was published, but there is an easy way to solve this right now as follows:

我知道这个问题很老,答案在发布时有所帮助,但现在有一种简单的方法可以解决这个问题,如下所示:

if ((dataTableName?.Rows?.Count ?? 0) > 0)

回答by haldo

As of C# 6.0 you can use the Null conditional operator?.(or ?[]for arrays).

从 C# 6.0 开始,您可以使用Null 条件运算符?.(或?[]用于数组)。

The null conditional operator simplifies the statement to:

null 条件运算符将语句简化为:

if (dt?.Rows?.Count > 0)

This returns false when:

在以下情况下返回 false:

  1. the data table dtis null
  2. data table Rows dt.Rowsis null
  3. the number of rows dt.Rows.Countis 0
  1. 数据表dt为空
  2. 数据表行为dt.Rows
  3. 行数dt.Rows.Count为 0

Using the null conditional operator you can avoid manually checking both the data table and count properties, eg if (dt != null && dt.Rows.Count > 0)

使用空条件运算符可以避免手动检查数据表和计数属性,例如 if (dt != null && dt.Rows.Count > 0)