可以使用以下代码连接SQL Server,并获取查询数据的行数:

using System.Data.SqlClient;

// 连接字符串
string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";

// SQL 查询语句
string sqlQuery = "SELECT * FROM yourTableName";

// 创建连接对象
SqlConnection connection = new SqlConnection(connectionString);

// 创建命令对象
SqlCommand command = new SqlCommand(sqlQuery, connection);

// 打开连接
connection.Open();

// 执行查询,并获取结果集
SqlDataReader reader = command.ExecuteReader();

// 遍历结果集,统计行数
int rowCount = 0;
while (reader.Read())
{
    rowCount++;
}

// 关闭连接
connection.Close();

// 输出行数
Console.WriteLine("查询结果共有 " + rowCount + " 行。");

注意,上述代码仅适用于查询结果比较小的情况,如果查询结果较大,建议使用分页查询的方式获取数据


原文地址: https://www.cveoy.top/t/topic/hiyt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录