在 C# 中连接数据库的步骤:创建连接字符串,包含数据库信息。创建连接对象,使用 SqlConnection 类。打开连接,使用 Open() 方法。执行查询或命令,使用 SqlCommand 类。关闭连接,使用 Close() 方法。

使用 C# 窗体连接数据库
在 C# 中,连接数据库需要以下步骤:
1. 创建连接字符串
连接字符串包含连接到数据库所需的信息,如服务器地址、数据库名称、用户名和密码。例如:
string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True;";
2. 创建连接对象
使用 System.Data.SqlClient 命名空间中的 SqlConnection 类创建连接对象。如下所示:
using (SqlConnection connection = new SqlConnection(connectionString))
{
// ...
}3. 打开连接
使用 Open() 方法打开连接。
connection.Open();
4. 执行查询或命令
使用 SqlCommand 类执行查询或命令。如下示例执行一个查询:
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM Customers";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["CustomerID"].ToString());
}
}5. 关闭连接
使用 Close() 方法关闭连接。
connection.Close();
附加说明:
- 使用
using语句确保连接在不再需要时自动关闭。 -
Integrated Security=True表示使用 Windows 身份验证连接。 - 请确保应用程序具有连接所用数据库和服务器的访问权限。










