c# 数据库获取数据
时间: 2023-12-26 20:05:22 浏览: 73
使用数据集读取数据-ADO.NET—C#数据库访问
以下是使用C#获取数据库数据的示例代码:
```csharp
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Data Source=serverName;Initial Catalog=databaseName;User ID=userName;Password=password";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM tableName";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 从数据库中获取数据
int id = (int)reader["id"];
string name = (string)reader["name"];
DateTime date = (DateTime)reader["date"];
// 处理数据
Console.WriteLine("ID: " + id);
Console.WriteLine("Name: " + name);
Console.WriteLine("Date: " + date);
Console.WriteLine();
}
reader.Close();
}
}
}
```
请注意,上述代码中的`serverName`、`databaseName`、`userName`、`password`和`tableName`需要根据实际情况进行替换。
阅读全文