从SQL Server表中读取行

本文关键字:读取 SQL Server | 更新日期: 2023-09-27 18:15:51

此代码仅读取ID 1,我需要读取所有表。我该怎么做呢?

using (SqlConnection sqlConnection = new SqlConnection())
{
    sqlConnection.ConnectionString = "Data Source=TOMMY-PC''SQLEXPRESS; Initial Catalog=Test; Integrated Security=True;";
    sqlConnection.Open();
    SqlCommand sqlCommand = new SqlCommand("SELECT * FROM dbo.Users");
    sqlCommand.Connection = sqlConnection;
    SqlDataAdapter adapter = new SqlDataAdapter();
    DataTable table = new DataTable();
    adapter.SelectCommand = sqlCommand;
    adapter.Fill(table);
    if ((string)table.Rows[0]["Name"] == textBox2.Text)
    {
        MessageBox.Show("Founded");
    }
}

从SQL Server表中读取行

如果您试图查找具有特定名称的用户是否存在,那么您不需要读取整个表,但您可以编写一个查询来发现具有该名称的用户是否存在

using (SqlConnection sqlConnection = new SqlConnection())
using (SqlCommand sqlCommand = new SqlCommand())
{
    sqlConnection.ConnectionString = "....."";
    sqlCommand.Connection = sqlConnection;
    sqlCommand.CommandText = @"SELECT COUNT(*) FROM dbo.Users 
                        WHERE Name = @name";
    sqlConnection.Open();
    sqlCommand.Parameters.Add("@name", SqlDbType.NVarChar).Value = textBox2.Text;
    int result = Convert.ToInt32(sqlCommand.ExecuteNonQuery());
    if(result > 0) 
        MessageBox.Show("Founded " + result + " user/s");
    else
        MessageBox.Show("No user found with that name");
}

要回答您的直接问题:您需要执行foreach循环,如下所示:

foreach (var row in table.Rows.Cast<DataRow>())
{
    var name = row["Name"];
    //Continue here
}

说明Cast方法的使用:

类型为DataRowCollectiontable.Rows实现了旧的IEnumerable接口,该接口枚举行,但将行作为类型为object而不是DataRow的对象。我们使用cast方法将它们强制转换为DataRow