写一个C# DBhelper类
时间: 2024-11-13 18:22:21 浏览: 4
DBHelper类在C#中通常用于封装数据库操作,简化数据访问层的代码。下面是一个简单的例子,展示了如何创建一个基本的DbHelper类,该类提供增删改查的功能:
```csharp
using System.Data.SqlClient;
using System.Data;
public class DBHelper
{
private readonly string connectionString = "your_connection_string_here"; // 替换为实际的数据库连接字符串
public DBHelper()
{
// 数据库连接初始化
}
// 插入数据方法
public int Insert(string tableName, Dictionary<string, object> data)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = $"INSERT INTO {tableName} ({string.Join(",", data.Keys)}) VALUES ({string.Join(",", data.Values)})";
SqlCommand command = new SqlCommand(query, connection);
return command.ExecuteNonQuery();
}
}
// 更新数据方法
public int Update(string tableName, string keyValueColumn, object keyValue, Dictionary<string, object> updateData)
{
string whereClause = $"{keyValueColumn} = {keyValue}";
string setClause = string.Join(", ", $"{k} = {v}" for (k, v) in updateData);
string query = $"UPDATE {tableName} SET {setClause} WHERE {whereClause}";
// ...(其余代码与Insert类似,使用SqlCommand执行更新)
}
// 删除数据方法
public bool Delete(string tableName, string keyValueColumn, object keyValue)
{
string whereClause = $"{keyValueColumn} = {keyValue}";
string query = $"DELETE FROM {tableName} WHERE {whereClause}";
// ...(同理,使用SqlCommand执行删除并返回影响行数判断是否成功)
}
// 查询数据方法,这里仅示例了查询所有数据,可根据需要添加复杂查询
public DataTable SelectAll(string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand($"SELECT * FROM {tableName}", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
}
```
阅读全文