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[i]);
                }
            }
            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[i]);
                }
            }
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt=new DataTable();
            da.Fill(dt);
            return dt;
        }
    }
}

C#三层架构第五课之DBUtil层设计

上一篇:ORACLE 表的操作


下一篇:macos django 导入使用MySQL错误 django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib