c#连接SQLserve
时间: 2023-12-07 18:37:40 浏览: 93
使用C#连接SQL Server数据库
3星 · 编辑精心推荐
以下是C#连接SQL Server的示例代码:
```csharp
using System.Data.SqlClient;
// 创建连接字符串
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "服务器名称";
scsb.UserID = "用户名";
scsb.Password = "密码";
scsb.InitialCatalog = "数据库名称";
// 创建连接
SqlConnection SqlCon = new SqlConnection(scsb.ToString());
// 打开数据库
try
{
SqlCon.Open();
Console.WriteLine("数据库连接成功!");
}
catch (Exception ex)
{
Console.WriteLine("数据库连接失败:" + ex.Message);
}
// 执行SQL语句
string sql = "SELECT * FROM 表名";
SqlCommand cmd = new SqlCommand(sql, SqlCon);
SqlDataReader reader = cmd.ExecuteReader();
// 处理查询结果
while (reader.Read())
{
Console.WriteLine(reader["列名1"].ToString() + " " + reader["列名2"].ToString());
}
// 关闭连接
SqlCon.Close();
```
阅读全文