sqlSEVER C#例程
时间: 2024-02-04 22:08:17 浏览: 112
以下是一个使用C#编写的SQL Server例程的示例:
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
public class Program
{
public static void Main()
{
string connectionString = "Data Source=your_server_name;Initial Catalog=your_database_name;User ID=your_username;Password=your_password";
// 创建连接对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打开连接
connection.Open();
// 创建命令对象
using (SqlCommand command = new SqlCommand("SELECT * FROM user_table", connection))
{
// 执行查询并获取结果集
using (SqlDataReader reader = command.ExecuteReader())
{
// 遍历结果集并输出数据
while (reader.Read())
{
int userId = (int)reader["user_id"];
string userName = (string)reader["user_name"];
Console.WriteLine("User ID: " + userId);
Console.WriteLine("User Name: " + userName);
Console.WriteLine();
}
}
}
}
}
}
```
请注意,上述代码中的`your_server_name`、`your_database_name`、`your_username`和`your_password`需要替换为实际的数据库连接信息。
阅读全文