C#三层架构第五课之DBUtil层设计
DBUtil层设计一般用来设计通用的数据库连接类或者其他字符编码处理、IO处理等通用类的设计。参考代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace DbUtil
{
public class DBHelper
{
//增删改:可以封装到一个方法;
/// <summary>
///
/// </summary>
/// <param name="sql">sql语句,insert update delte</param>
/// <param name="parameters">list:集合;动态添加数据;长度不固定</param>
/// <returns></returns>
public static bool update(String sql,List<SqlParameter>parameters) {
String url = "server=.;database=MyDb;uid=sa;pwd=123456";
//1.链接对象;
SqlConnection conn = new SqlConnection(url);
conn.Open();
//2.SqlCommand
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
if (parameters != null)
{
//继续添加参数;
for (int i = 0; i < parameters.Count; i++)
{
cmd.Parameters.Add(parameters);
}
}
int result=cmd.ExecuteNonQuery();
if (result > 0)
return true;
return false;
}
public static DataTable query(String sql, List<SqlParameter> parameters)
{
String url = "server=.;database=MyDb;uid=sa;pwd=123456";
//1.链接对象;
SqlConnection conn = new SqlConnection(url);
conn.Open();
//2.SqlCommand
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
if (parameters != null)
{
//继续添加参数;
for (int i = 0; i < parameters.Count; i++)
{
cmd.Parameters.Add(parameters);
}
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
return dt;
}
}
}
文档来源:51CTO技术博客https://blog.51cto.com/u_2096101/3185701
页:
[1]