[英]Reading rows from a SQL Server table
This code only read ID 1 and I need to read all table. 此代码仅读取ID 1,我需要读取所有表。 How can I go about this? 我该怎么办?
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");
}
}
To answer your direct question: you need to do a foreach loop, like this: 要回答您的直接问题:您需要执行一个foreach循环,如下所示:
foreach (var row in table.Rows.Cast<DataRow>())
{
var name = row["Name"];
//Continue here
}
To explain the use of the Cast
method: 解释Cast
方法的用法:
The table.Rows
which is of type DataRowCollection
implements the older IEnumerable interface which enumerates over the rows but give us the rows as objects of type object
not DataRow
. 类型为DataRowCollection
的table.Rows
实现了较旧的IEnumerable接口,该接口table.Rows
,但将行作为对象而不是DataRow
类型的object
提供给我们。 We cast them to DataRow
by using the Cast method. 我们使用Cast方法将它们转换为DataRow
。
If you are trying to find if a user with a specific name exists or not, then you don't need to read the whole table, but you could write a query that discovers if users with that name exist or not 如果要查找是否存在具有特定名称的用户,则无需读取整个表,但是可以编写查询以发现具有该名称的用户是否存在
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.