上一篇
c#语句连接sql数据库
- 行业动态
- 2025-05-12
- 7
在C#中可通过
System.Data.SqlClient
命名空间连接SQL数据库,使用 SqlConnection
对象配置连接字符串,指定服务器、数据库及认证信息,通过 Open()
方法建立连接,配合 SqlCommand
执行SQL语句,最后用 Close()
或 using
代码块释放资源,确保异常处理与数据安全。
环境准备
开发工具要求
- Visual Studio 2019或更高版本
- .NET Framework 4.8+ 或 .NET Core 3.1+
- SQL Server 2016+ 或 Azure SQL Database
NuGet包安装
通过NuGet包管理器安装System.Data.SqlClient
(适用于.NET Framework)或Microsoft.Data.SqlClient
(推荐用于.NET Core/5+)。
连接数据库的核心步骤
构建连接字符串
连接字符串包含数据库地址、认证信息等关键参数,建议使用SqlConnectionStringBuilder
类动态生成:
var builder = new SqlConnectionStringBuilder { DataSource = "服务器名或IP", InitialCatalog = "数据库名", UserID = "用户名", Password = "密码", ConnectTimeout = 30, // 连接超时时间(秒) IntegratedSecurity = false // 是否使用Windows身份验证 }; string connectionString = builder.ConnectionString;
创建并打开连接
使用using
语句确保资源自动释放:
using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); // 执行数据库操作... } catch (SqlException ex) { Console.WriteLine($"连接失败: {ex.Message}"); } }
执行数据库操作
查询数据示例
string sql = "SELECT UserId, UserName FROM Users WHERE Age > @Age"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@Age", 18); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine($"ID: {reader["UserId"]}, 姓名: {reader["UserName"]}"); } } }
插入数据示例
string insertSql = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)"; using (SqlCommand cmd = new SqlCommand(insertSql, connection)) { cmd.Parameters.AddWithValue("@Name", "无线鼠标"); cmd.Parameters.AddWithValue("@Price", 299.99); int rowsAffected = cmd.ExecuteNonQuery(); Console.WriteLine($"已插入{rowsAffected}行"); }
安全与性能优化
防SQL注入
- 强制使用参数化查询(如上文示例)
- 禁止拼接SQL字符串
连接池管理
- 默认启用连接池,无需手动配置
- 通过
Max Pool Size
调整最大连接数builder.MaxPoolSize = 100; // 设置连接池上限
异常处理
- 捕获特定异常类型:
catch (SqlException ex) when (ex.Number == 18456) { Console.WriteLine("登录失败:用户名或密码错误"); }
- 捕获特定异常类型:
常见问题解答
问题现象 | 解决方案 |
---|---|
连接超时 | 检查网络连通性,增加ConnectTimeout 值 |
“Login failed for user” | 验证SQL Server身份验证模式是否启用 |
连接池耗尽 | 检查是否未关闭连接,调整Max Pool Size |
扩展知识
- 异步操作:使用
OpenAsync()
和ExecuteReaderAsync()
提升并发性能 - 加密连接:在连接字符串中添加
Encrypt=True
启用TLS加密 - 配置文件管理:将连接字符串存储在
appsettings.json
中
引用说明
本文代码示例参考自:
- Microsoft Learn文档:使用 ADO.NET 连接到 SQL 数据库
- SQL Server官方安全指南:防止 SQL 注入
通过遵循以上实践方法,开发者可以构建安全可靠的数据库连接方案,建议定期检查数据库连接代码,及时应用安全补丁和性能优化措施。