这是一个通用的DBHelper的类文件
using System.Collections.Generic;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;
namespace Reflectiones
{
public class DBHelper
{
/// <summary>
/// 显示数据
/// </summary>
/// <param name=\"t\"></param>
/// <returns></returns>
public List<T> GetData<T>(T t) where T:class,new()
{
List<T> lst = new List<T>();
var tf = typeof(T);
string sql = \"SELECT * FROM\" + tf.Name;//Model层的类名
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(\"\"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
PropertyInfo[] infos = tf.GetProperties();
for (int i = 0; i < dt.Rows.Count; i++)
{
t = new T();
foreach (var item in infos)
{
item.SetValue(t, dt.Rows[i][item.Name]);
}
lst.Add(t);
}
return lst;
}
public int ComSqlCreate<T>(T t)where T:class,new()
{
var tf = typeof(T);
string sql = \"INSERT INTO \" + tf.Name + \" VALUES(\";
PropertyInfo[] infos = tf.GetProperties();
foreach (var item in infos)
{
if (item.GetCustomAttribute(typeof(KeyAttribute),true) == null)
{
sql += \"\'\" + item.GetValue(t, null) + \"\',\";
}
}
sql += sql.TrimEnd(\',\') + \")\";
using (SqlConnection conn = new SqlConnection(\"\"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
int n = cmd.ExecuteNonQuery();
return n;
}
}
/// <summary>
/// 修改数据
/// </summary>
/// <typeparam name=\"T\"></typeparam>
/// <param name=\"t\"></param>
/// <returns></returns>
public int ComSqlUpdate<T>(T t) where T:class,new()
{
var tf = typeof(T);
string sql = \"UPDATE \" + tf.Name + \" SET \";
string sqlWhere = \" WHERE \";
PropertyInfo[] infos = tf.GetProperties();
foreach (var item in infos)
{
if (item.Name == \"ID\")
{
sqlWhere += \" WHERE \"+ item.Name + \" = \'\" + item.GetValue(t, null) + \"\'\";
}
else
{
sql += item.Name + \" = \'\" + item.GetValue(t, null) + \"\',\";
}
}
sql = sql.TrimEnd(\',\') + sqlWhere;
using (SqlConnection conn = new SqlConnection(\"\"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
int n = cmd.ExecuteNonQuery();
return n;
}
}
/// <summary>
/// 删除数据
/// </summary>
/// <typeparam name=\"T\"></typeparam>
/// <param name=\"t\"></param>
/// <returns></returns>
public int ComSqlDelete<T>(T t)where T:class,new()
{
var tf = typeof(T);
PropertyInfo[] infos = tf.GetProperties();
string sql = \"DELETE FROM \" + tf.Name;
foreach (var item in infos)
{
if (item.Name == \"ID\")
{
sql += \" WHERE \" + item.Name + \" = \'\" + item.GetValue(t, null) + \"\'\";
}
}
using (SqlConnection conn = new SqlConnection(\"\"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
int n = cmd.ExecuteNonQuery();
return n;
}
}
}
}
继续阅读与本文标签相同的文章
上一篇 :
LeetCode-40. 组合总和 II
-
阿里云服务器搭建一个网站网站建设的基本步骤——部署与发布新手入门
2026-05-18栏目: 教程
-
网络基础技术实践#网络安全基础技术实践课程
2026-05-18栏目: 教程
-
阿里云服务器计算网络增强型实例sn1ne 适合中大型网站及性能要求高的公司业务使用
2026-05-18栏目: 教程
-
前端进阶|第八天 京东笔试题,引用传参赋值无效?
2026-05-18栏目: 教程
-
阿里云弹性伸缩ESS必知必会
2026-05-18栏目: 教程
