在C#中连接到SQL Server数据库,你可以使用System.Data.SqlClient
命名空间中的SqlConnection
类。以下是连接到SQL Server数据库的基本步骤和示例代码:
步骤 1: 引入命名空间
using System.Data.SqlClient; // 引入SQL Server连接命名空间
步骤 2: 创建连接字符串
连接字符串包含了连接到数据库所需的所有信息,如服务器地址、数据库名称、认证信息等。
string connectionString = @"Server=L5318819A251\SQLEXPRESS;Database=BooKMS;Integrated Security=True;";
这里的连接字符串包括:
Server
:指定了SQL Server实例的地址,\SQLEXPRESS
是实例名称。Database
:指定了要连接的数据库名称。Integrated Security
:设置为True
表示使用Windows身份验证。
步骤 3: 创建并打开连接
使用连接字符串创建SqlConnection
对象,然后打开这个连接。
SqlConnection conn = new SqlConnection(connectionString);
try
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
Console.WriteLine("Connection successful!");
// 执行数据库操作...
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred while connecting to the database: " + ex.Message);
}
步骤 4: 执行数据库操作
一旦连接打开,你可以执行SQL命令或查询,例如使用SqlCommand
对象。
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// 处理每一行数据...
Console.WriteLine(reader["YourColumnName"].ToString());
}
reader.Close();
步骤 5: 关闭连接
完成数据库操作后,不要忘记关闭连接和释放资源。
示例代码
这是一个简单的示例,演示了如何连接到SQL Server并从表中读取数据:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = @"Server=L5318819A281\SQLEXPRESS;Database=BooKMS;Integrated Security=True;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
Console.WriteLine("Connected to the database successfully!");
string sql = "SELECT * FROM YourTable";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// 替换YourColumnName为你的表中的列名
Console.WriteLine(reader["YourColumnName"].ToString());
}
}
}
}
catch (SqlException e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
}