c#sql语句循环填充Datetable
时间: 2023-06-29 07:02:42 浏览: 103
以下是一个使用 C# 和 SQL Server 的示例代码,使用循环填充 DataTable:
```csharp
using System.Data;
using System.Data.SqlClient;
// 假设已经设置好了 SQL Server 的连接字符串
string connectionString = "Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True";
// 创建 DataTable
DataTable dataTable = new DataTable("MyTable");
// 创建列
dataTable.Columns.Add("Column1", typeof(int));
dataTable.Columns.Add("Column2", typeof(string));
dataTable.Columns.Add("Column3", typeof(DateTime));
// 使用 SQL 查询数据
string sqlQuery = "SELECT Column1, Column2, Column3 FROM MyTable";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlQuery, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// 循环读取数据并填充 DataTable
while (reader.Read())
{
DataRow row = dataTable.NewRow();
row["Column1"] = reader.GetInt32(0);
row["Column2"] = reader.GetString(1);
row["Column3"] = reader.GetDateTime(2);
dataTable.Rows.Add(row);
}
reader.Close();
}
// 现在 DataTable 已经填充完成,可以使用它进行其他操作
```
注意,以上代码仅供参考,具体实现方式可能因为实际情况而有所不同。
阅读全文
相关推荐
















