上一篇
C如何高效实现数据库插入操作?
- 行业动态
- 2025-05-14
- 3
在C#中通过SqlConnection建立数据库连接,使用SqlCommand对象构造INSERT语句,推荐参数化查询防止SQL注入,通过ExecuteNonQuery执行插入操作,注意异常处理和资源释放,也可通过ORM框架如Entity Framework简化数据操作流程。
使用ADO.NET实现基础插入
以下是使用SqlConnection
和SqlCommand
类的基本操作流程:
using System.Data.SqlClient; // 定义连接字符串(需替换实际值) string connectionString = "Server=YourServer;Database=YourDB;User Id=YourUser;Password=YourPassword;"; // 定义插入SQL语句 string sql = "INSERT INTO Users (Name, Age, Email) VALUES ('张三', 25, 'zhangsan@example.com')"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(sql, connection)) { int rowsAffected = command.ExecuteNonQuery(); Console.WriteLine($"成功插入 {rowsAffected} 行"); } }
代码说明:
SqlConnection
管理数据库连接,using
确保资源释放ExecuteNonQuery()
执行非查询类SQL语句,返回受影响行数- 硬编码值仅用于演示,实际生产需参数化(下文详述)
参数化查询防止SQL注入
直接拼接SQL存在安全风险,推荐使用SqlParameter
:
string sql = "INSERT INTO Users (Name, Age, Email) VALUES (@Name, @Age, @Email)"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@Name", "李四"); command.Parameters.AddWithValue("@Age", 30); command.Parameters.AddWithValue("@Email", "lisi@example.com"); command.ExecuteNonQuery(); }
为何重要:
- 避免反面SQL注入攻击
- 自动处理数据类型转换(如日期、字符串转义)
- 提升代码可读性与维护性
Entity Framework Core操作(推荐)
通过ORM框架简化数据库操作:
定义数据模型
public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } }
创建DbContext
public class AppDbContext : DbContext { public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer("Your_Connection_String"); }
执行插入
using (var context = new AppDbContext()) { var user = new User { Name = "王五", Age = 28, Email = "wangwu@example.com" }; context.Users.Add(user); context.SaveChanges(); }
优势:
- 无需手动编写SQL
- 支持事务、迁移等高级功能
- 强类型检查降低错误概率
异常处理与日志记录
数据库操作需包含错误处理机制:
try { using (var connection = new SqlConnection(connectionString)) { // 执行操作... } } catch (SqlException ex) { Console.WriteLine($"数据库错误:{ex.Message}"); // 记录日志:Log.Error(ex, "插入数据失败"); } catch (Exception ex) { Console.WriteLine($"未知错误:{ex.Message}"); }
建议:
- 分类捕获
SqlException
和通用异常 - 记录详细日志(如操作时间、SQL语句、错误堆栈)
- 避免向用户暴露原始错误信息
最佳实践总结
- 参数化查询:始终使用
SqlParameter
或ORM框架避免SQL注入 - 资源释放:对
SqlConnection
、SqlCommand
等对象使用using
语句 - 连接管理:
- 从配置文件读取连接字符串(如
appsettings.json
) - 使用连接池(默认启用)
- 从配置文件读取连接字符串(如
- 性能优化:
- 批量插入时考虑
SqlBulkCopy
- EF Core批量操作使用
AddRange()
+SaveChangesAsync()
- 批量插入时考虑
- 事务处理:对多个相关操作启用事务
引用说明
- Microsoft ADO.NET文档:https://learn.microsoft.com/zh-cn/dotnet/framework/data/adonet/
- Entity Framework Core指南:https://learn.microsoft.com/zh-cn/ef/core/
- OWASP SQL注入防护建议:https://owasp.org/www-community/attacks/SQL_Injection