C#操作MySQL数据库 简单三层结构设计UI、BLL、DAL、Model实际项目应用例子

在实际项目中,程序设计都有他的层次结构,比如MVC、MVP、普通的三层结构等等,不过现在用三层结构的相比可能少了,但是也有一些小型项目还是挺实用的

1.介绍

普通的三层架构(BLL,DAL,Model)

1)实体(Model),用来创建对象的实体;

2)业务逻辑层(BLL),用来处理复杂的数据间的关系或者是业务间的关系;

3)数据库访问层(DAL),用来用来访问数据库的;

当然还会有,View(视图层),用来展示数据;

2.三层结构例子

2.1创建数据库并创建一张测试表

这里我用的Mysql

/*
Navicat MySQL Data Transfer Source Server : JiYFMySQL
Source Server Version : 50553
Source Host : localhost:3306
Source Database : testdemo Target Server Type : MYSQL
Target Server Version : 50553
File Encoding : 65001 Date: 2019-01-26 11:06:05
*/ SET FOREIGN_KEY_CHECKS=0; -- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(8) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`age` int(8) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '燕子', '25');
INSERT INTO `user` VALUES ('2', 'lisi', '15');
INSERT INTO `user` VALUES ('3', 'wangwu', '15');

数据库表如下

2.2创建实体类

     /// <summary>
/// user:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public partial class user
{
public user()
{}
#region Model
private int _id;
private string _name;
private int? _age;
/// <summary>
///
/// </summary>
public int id
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
public string name
{
set{ _name=value;}
get{return _name;}
}
/// <summary>
///
/// </summary>
public int? age
{
set{ _age=value;}
get{return _age;}
}
#endregion Model }

2.3  DAL的User类设计

 using System;
using System.Data;
using System.Text;
using MySql.Data.MySqlClient;
using Maticsoft.DBUtility;
using System.Data.SqlClient;//Please add references
namespace BenNH.DAL
{
/// <summary>
/// 数据访问类:user
/// </summary>
public partial class user
{
public user()
{}
#region BasicMethod /// <summary>
/// 增加一条数据
/// </summary>
public bool Add(BenNH.Model.user model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into user(");
strSql.Append("id,name,age)");
strSql.Append(" values (");
strSql.Append("@id,@name,@age)");
MySqlParameter[] parameters = {
new MySqlParameter("@id", MySqlDbType.Int32,),
new MySqlParameter("@name", MySqlDbType.VarChar,),
new MySqlParameter("@age", MySqlDbType.Int32,)};
parameters[].Value = model.id;
parameters[].Value = model.name;
parameters[].Value = model.age; int rows=DbHelperMySQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > )
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(BenNH.Model.user model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update user set ");
strSql.Append("name=@name,");
strSql.Append("age=@age");
strSql.Append(" where id=@id ");
MySqlParameter[] parameters = {
new MySqlParameter("@name", MySqlDbType.VarChar,),
new MySqlParameter("@age", MySqlDbType.Int32,),
new MySqlParameter("@id", MySqlDbType.Int32,)};
parameters[].Value = model.name;
parameters[].Value = model.age;
parameters[].Value = model.id; int rows=DbHelperMySQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > )
{
return true;
}
else
{
return false;
}
} /// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(long id)
{
//该表无主键信息,请自定义主键/条件字段
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from user ");
strSql.Append(" where id=@userID");
MySqlParameter[] parameters = {
new MySqlParameter("@@userID", SqlDbType.BigInt)
}; parameters[].Value = id; int rows=DbHelperMySQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > )
{
return true;
}
else
{
return false;
}
} /// <summary>
/// 得到一个对象实体
/// </summary>
public BenNH.Model.user GetModel()
{
//该表无主键信息,请自定义主键/条件字段
StringBuilder strSql=new StringBuilder();
strSql.Append("select id,name,age from user ");
strSql.Append(" where ");
MySqlParameter[] parameters = {
}; BenNH.Model.user model=new BenNH.Model.user();
DataSet ds=DbHelperMySQL.Query(strSql.ToString(),parameters);
if(ds.Tables[].Rows.Count>)
{
return DataRowToModel(ds.Tables[].Rows[]);
}
else
{
return null;
}
} /// <summary>
/// 得到一个对象实体
/// </summary>
public BenNH.Model.user DataRowToModel(DataRow row)
{
BenNH.Model.user model=new BenNH.Model.user();
if (row != null)
{
if(row["id"]!=null && row["id"].ToString()!="")
{
model.id=int.Parse(row["id"].ToString());
}
if(row["name"]!=null)
{
model.name=row["name"].ToString();
}
if(row["age"]!=null && row["age"].ToString()!="")
{
model.age=int.Parse(row["age"].ToString());
}
}
return model;
} /// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select id,name,age ");
strSql.Append(" FROM user ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
return DbHelperMySQL.Query(strSql.ToString());
} /// <summary>
/// 获取记录总数
/// </summary>
public int GetRecordCount(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) FROM user ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString());
if (obj == null)
{
return ;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("SELECT * FROM ( ");
strSql.Append(" SELECT ROW_NUMBER() OVER (");
if (!string.IsNullOrEmpty(orderby.Trim()))
{
strSql.Append("order by T." + orderby );
}
else
{
strSql.Append("order by T. desc");
}
strSql.Append(")AS Row, T.* from user T ");
if (!string.IsNullOrEmpty(strWhere.Trim()))
{
strSql.Append(" WHERE " + strWhere);
}
strSql.Append(" ) TT");
strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
return DbHelperMySQL.Query(strSql.ToString());
} /*
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
MySqlParameter[] parameters = {
new MySqlParameter("@tblName", MySqlDbType.VarChar, 255),
new MySqlParameter("@fldName", MySqlDbType.VarChar, 255),
new MySqlParameter("@PageSize", MySqlDbType.Int32),
new MySqlParameter("@PageIndex", MySqlDbType.Int32),
new MySqlParameter("@IsReCount", MySqlDbType.Bit),
new MySqlParameter("@OrderType", MySqlDbType.Bit),
new MySqlParameter("@strWhere", MySqlDbType.VarChar,1000),
};
parameters[0].Value = "user";
parameters[1].Value = "";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperMySQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}*/ #endregion BasicMethod
#region ExtensionMethod #endregion ExtensionMethod
}
}

2.4 BLL的User类设计

 using System;
using System.Data;
using System.Collections.Generic;
using Maticsoft.Common;
using BenNH.Model;
namespace BenNH.BLL
{
/// <summary>
/// user
/// </summary>
public partial class user
{
private readonly BenNH.DAL.user dal=new BenNH.DAL.user();
public user()
{}
#region BasicMethod /// <summary>
/// 增加一条数据
/// </summary>
public bool Add(BenNH.Model.user model)
{
return dal.Add(model);
} /// <summary>
/// 更新一条数据
/// </summary>
public bool Update(BenNH.Model.user model)
{
return dal.Update(model);
} /// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(long id)
{
//该表无主键信息,请自定义主键/条件字段
return dal.Delete(id);
} /// <summary>
/// 得到一个对象实体
/// </summary>
public BenNH.Model.user GetModel()
{
//该表无主键信息,请自定义主键/条件字段
return dal.GetModel();
} /// <summary>
/// 得到一个对象实体,从缓存中
/// </summary>
public BenNH.Model.user GetModelByCache()
{
//该表无主键信息,请自定义主键/条件字段
string CacheKey = "userModel-" ;
object objModel = Maticsoft.Common.DataCache.GetCache(CacheKey);
if (objModel == null)
{
try
{
objModel = dal.GetModel();
if (objModel != null)
{
int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache");
Maticsoft.Common.DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
}
}
catch{}
}
return (BenNH.Model.user)objModel;
} /// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
return dal.GetList(strWhere);
}
/// <summary>
/// 获得数据列表
/// </summary>
public List<BenNH.Model.user> GetModelList(string strWhere)
{
DataSet ds = dal.GetList(strWhere);
return DataTableToList(ds.Tables[]);
}
/// <summary>
/// 获得数据列表
/// </summary>
public List<BenNH.Model.user> DataTableToList(DataTable dt)
{
List<BenNH.Model.user> modelList = new List<BenNH.Model.user>();
int rowsCount = dt.Rows.Count;
if (rowsCount > )
{
BenNH.Model.user model;
for (int n = ; n < rowsCount; n++)
{
model = dal.DataRowToModel(dt.Rows[n]);
if (model != null)
{
modelList.Add(model);
}
}
}
return modelList;
} /// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetAllList()
{
return GetList("");
} /// <summary>
/// 分页获取数据列表
/// </summary>
public int GetRecordCount(string strWhere)
{
return dal.GetRecordCount(strWhere);
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
return dal.GetListByPage( strWhere, orderby, startIndex, endIndex);
}
/// <summary>
/// 分页获取数据列表
/// </summary>
//public DataSet GetList(int PageSize,int PageIndex,string strWhere)
//{
//return dal.GetList(PageSize,PageIndex,strWhere);
//} #endregion BasicMethod
#region ExtensionMethod #endregion ExtensionMethod
}
}

2.5MySQL帮助类

 using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
namespace Maticsoft.DBUtility
{
/// <summary>
/// 数据访问抽象基础类
/// Copyright (C) Maticsoft
/// </summary>
public abstract class DbHelperMySQL
{
//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.
public static string connectionString = PubConstant.ConnectionString;
public DbHelperMySQL()
{
} #region 公用方法
/// <summary>
/// 得到最大值
/// </summary>
/// <param name="FieldName"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return ;
}
else
{
return int.Parse(obj.ToString());
}
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 是否存在(基于MySqlParameter)
/// </summary>
/// <param name="strSql"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
#endregion #region 执行简单SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
} public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
} /// <summary>
/// 执行MySql和Oracle滴混合事务
/// </summary>
/// <param name="list">SQL命令行列表</param>
/// <param name="oracleCmdSqlList">Oracle命令行列表</param>
/// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns>
public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
MySqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
foreach (CommandInfo myDE in list)
{
string cmdText = myDE.CommandText;
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
PrepareCommand(cmd, conn, tx, cmdText, cmdParms);
if (myDE.EffentNextType == EffentNextType.SolicitationEvent)
{
if (myDE.CommandText.ToLower().IndexOf("count(") == -)
{
tx.Rollback();
throw new Exception("违背要求"+myDE.CommandText+"必须符合select count(..的格式");
//return 0;
} object obj = cmd.ExecuteScalar();
bool isHave = false;
if (obj == null && obj == DBNull.Value)
{
isHave = false;
}
isHave = Convert.ToInt32(obj) > ;
if (isHave)
{
//引发事件
myDE.OnSolicitationEvent();
}
}
if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
{
if (myDE.CommandText.ToLower().IndexOf("count(") == -)
{
tx.Rollback();
throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式");
//return 0;
} object obj = cmd.ExecuteScalar();
bool isHave = false;
if (obj == null && obj == DBNull.Value)
{
isHave = false;
}
isHave = Convert.ToInt32(obj) > ; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
{
tx.Rollback();
throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0");
//return 0;
}
if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
{
tx.Rollback();
throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0");
//return 0;
}
continue;
}
int val = cmd.ExecuteNonQuery();
if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == )
{
tx.Rollback();
throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行");
//return 0;
}
cmd.Parameters.Clear();
}
string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC");
bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList);
if (!res)
{
tx.Rollback();
throw new Exception("执行失败");
// return -1;
}
tx.Commit();
return ;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
tx.Rollback();
throw e;
}
catch (Exception e)
{
tx.Rollback();
throw e;
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static int ExecuteSqlTran(List<String> SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
MySqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
int count = ;
for (int n = ; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > )
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return ;
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static object ExecuteSqlGet(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
} /// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
public static object GetSingle(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string strSQL)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
try
{
connection.Open();
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
} }
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
public static DataSet Query(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
} #endregion #region 执行带参数的SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{ int count = ;
//循环
foreach (CommandInfo myDE in cmdList)
{
string cmdText = myDE.CommandText;
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
{
if (myDE.CommandText.ToLower().IndexOf("count(") == -)
{
trans.Rollback();
return ;
} object obj = cmd.ExecuteScalar();
bool isHave = false;
if (obj == null && obj == DBNull.Value)
{
isHave = false;
}
isHave = Convert.ToInt32(obj) > ; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
{
trans.Rollback();
return ;
}
if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
{
trans.Rollback();
return ;
}
continue;
}
int val = cmd.ExecuteNonQuery();
count += val;
if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == )
{
trans.Rollback();
return ;
}
cmd.Parameters.Clear();
}
trans.Commit();
return count;
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = ;
//循环
foreach (CommandInfo myDE in SQLStringList)
{
string cmdText = myDE.CommandText;
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = ;
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
} /// <summary>
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
// finally
// {
// cmd.Dispose();
// connection.Close();
// } } /// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
} private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{ foreach (MySqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
} #endregion } }

2.6应用程序创建app.config配置文件(注意链接字符串和自己的数据库对应)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<!-- 连接字符串是否加密 -->
<add key="ConStringEncrypt" value="false"/>
<!-- 数据库连接字符串,(如果采用加密方式,上面一项要设置为true
如果使用明文这样server=127.0.0.1;database=.....,上面则设置为false。 -->
<add key="ConnectionString" value="server=127.0.0.1;database=TestDemo;uid=root;pwd=root"/>
<!--其它模块连接字符串,可以不断增加以便同一个项目支持连接多个数据库。如果没有,可以删除该行-->
<add key="ConnectionString2" value="server=127.0.0.1;database=TestDemo;uid=root;pwd=root"/>
</appSettings>
</configuration>

3.0 测试程序

3.1创建简单的UI

3.2首先创建实体对象userModule和业务逻辑BLLUser对象

         public BenNH.Model.user userModule = new BenNH.Model.user();
public BenNH.BLL.user userBLL = new BenNH.BLL.user();

3.3 增、删、改、查 简单编写(这里没有严格判断等等)

查询

    /// <summary>
/// 查询
/// </summary>
private void Select()
{
this.dataGridView1.Rows.Clear();
//查
List<BenNH.Model.user> userlist = userBLL.GetModelList("");
foreach (BenNH.Model.user item in userlist)
{
DataGridViewRow row = new DataGridViewRow(); DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
cell.Value = item.id;
DataGridViewTextBoxCell cell2 = new DataGridViewTextBoxCell();
cell2.Value = item.name;
DataGridViewTextBoxCell cell3 = new DataGridViewTextBoxCell();
cell3.Value = item.age;
row.Cells.Add(cell);
row.Cells.Add(cell2);
row.Cells.Add(cell3); this.dataGridView1.Rows.Add(row);
}
this.label1.Text = "查询出user表:" + userlist.Count + "条记录"; int rowIndex = dataGridView1.CurrentRow.Index;
if (rowIndex < ) return; textBox1.Text = dataGridView1.Rows[rowIndex].Cells[].Value.ToString();
textBox2.Text = dataGridView1.Rows[rowIndex].Cells[].Value.ToString();
textBox3.Text = dataGridView1.Rows[rowIndex].Cells[].Value.ToString(); }

增加

   /// <summary>
/// 增加
/// </summary>
private void Add()
{ //增加
userModule.id = int.Parse(textBox1.Text);
userModule.name = textBox2.Text;
userModule.age = int.Parse(textBox3.Text); bool isAdd = userBLL.Add(userModule);
if (isAdd)
this.label2.Text = "增加数据成功"; this.Select();
}

删除

   /// <summary>
/// 删除
/// </summary>
private void Delete()
{
//删除
bool isDelete = userBLL.Delete(int.Parse(textBox1.Text));
if (isDelete)
this.label3.Text = "数据删除成功"; this.Select();
}

更新

 /// <summary>
/// 更新
/// </summary>
private void Update()
{
//修改
userModule.id = int.Parse(textBox1.Text);
userModule.name = textBox2.Text;
userModule.age = int.Parse(textBox3.Text); bool isUpdate = userBLL.Update(userModule);
if (isUpdate)
this.label4.Text = "修改数据成功"; this.Select();
}

4.测试

数据库数据

运行程序

可以进行简单的操作了

5.程序下载

目录结构

程序源代码工程下载

或者博客留言,给出邮箱,发你!

到这里就结束了,欢迎下载,爱你们呦,么么哒。。。。。❥(^_-)

小伙伴们,需要源代码的直接到这里下载: https://files.cnblogs.com/files/JiYF/BLL_Model_UI_MySql.rar

复制上面的地址到浏览器即可下载

C#简单三层结构设计UI、BLL、DAL、Model实际项目应用例子的更多相关文章

  1. Web三层-UI/BLL/DAL/MODEL

    2013传智播客视频\视频\2013-05-28-EF\视频 创建4个程序集,添加引用,model添加映射, P01UI表现层--BLL+MODELP02BLL业务层--DAL+MODELP03DAL ...

  2. 关于简单的三层的简化(bll,dal,model)的封装这里全部都在一个文件主要在于明白意思

    using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace 封装泛型CRU ...

  3. NHibernate框架与BLL+DAL+Model+Controller+UI 多层架构十分相似--『Spring.NET+NHibernate+泛型』概述、知识准备及介绍(一)

    原文://http://blog.csdn.net/wb09100310/article/details/47271555 1. 概述 搭建了Spring.NET+NHibernate的一个数据查询系 ...

  4. C#中三层架构UI、BLL、DAL、Model实际操作

    三层架构分为:表现层(UI).业务逻辑层(BLL).数据访问层(DAL)再加上实体类库(Model) 转载请注明出自朱朱家园https://blog.csdn.net/zhgl7688 1.实体类库( ...

  5. C#里面BLL、Model、DAL、UI层

    C# 三层架构分为:表现层(UI).业务逻辑层(BLL).数据访问层(DAL)再加上实体类库(Model) 1.实体类库(Model),主要存放数据库中的表字段. 操作: (1)先建立实体类库Mode ...

  6. 【转】asp.net mvc(模式)和三层架构(BLL、DAL、Model)的联系与区别

    原文地址:http://blog.csdn.net/luoyeyu1989/article/details/8275866 首先,MVC和三层架构,是不一样的. 三层架构中,DAL(数据访问层).BL ...

  7. asp.net mvc(模式)和三层架构(BLL、DAL、Model)的联系与区别 转载自:http://blog.csdn.net/luoyeyu1989/article/details/8275866

    首先,MVC和三层架构,是不一样的. 三层架构中,DAL(数据访问层).BLL(业务逻辑层).WEB层各司其职,意在职责分离. MVC是 Model-View-Controller,严格说这三个加起来 ...

  8. Asp.Net MVC简单三层架构(MVC5+EF6)

    三层架构与MVC的关系 三层架构是一个分层式的软件体系架构设计,分为:表现层(UI).业务逻辑层(BLL).数据访问层(DAL).分层的目的是为了实现“高内聚,低耦合”的思想,有利于系统后期的维护.更 ...

  9. .NET简单三层的理解

    1.UI 表示层 :就是我们看到的网站前台2.BLL 业务逻辑层:很简单 也很重要 处理逻辑问题 简单程序看不出啥效果3.DAL 数据访问层: 写数据连接和执行的SQL语句4.MODEL 模型层:封装 ...

随机推荐

  1. 【模拟】[NOIP2014]螺旋矩阵[c++]

    题目描述 一个n行n列的螺旋矩阵可由如下方法生成: 从矩阵的左上角(第1行第1列)出发,初始时向右移动:如果前方是未曾经过的格子,则继续前进,否则右转:重复上述操作直至经过矩阵中所有格子.根据经过顺序 ...

  2. js扩展运算符(spread)三个点(...)

    常见用法: 1.该运算符主要用于函数调用. function push(array, ...items) { array.push(...items); } function add(x, y) { ...

  3. [Python设计模式] 第19章 分公司=部门?——组合模式

    github地址:https://github.com/cheesezh/python_design_patterns 组合模式 组合模式,将对象组合成树形结构以表示"部分-整体" ...

  4. 如何快速申请苹果IOS个人开发者账号

    在上周我有一同事,他利用周末的时间自己做了一个IOS版本游戏类APP,用Unity3D开发的(抱着好玩的心态),于是他想发布到苹果App Store 上去.他没有苹果开发者账号,也没有购买过. 于是找 ...

  5. 【原创 Hadoop&Spark 动手实践 7】Spark 计算引擎剖析与动手实践

    [原创 Hadoop&Spark 动手实践 7]Spark计算引擎剖析与动手实践 目标: 1. 理解Spark计算引擎的理论知识 2. 动手实践更深入的理解Spark计算引擎的细节 3. 通过 ...

  6. 【转载】Hadoop官方文档翻译——HDFS Architecture 2.7.3

    HDFS Architecture HDFS Architecture(HDFS 架构) Introduction(简介) Assumptions and Goals(假设和目标) Hardware ...

  7. Asp.Net \uxxx Unicode编码解码

    /// <summary> /// Unicode编码 /// </summary> /// <param name="str"></pa ...

  8. Python之turtle画同心圆和棋盘

    画饼图 import turtle t = turtle.Pen() for i in range(5): t.penup() t.goto(0, -i*30) t.pendown() t.circl ...

  9. tf更新tensor/自定义层

    修改Tensor特定位置的值 如 stack overflow 中提到的方案. TensorFlow不让你直接单独改指定位置的值,但是留了个歪门儿,就是tf.scatter_update这个方法,它可 ...

  10. windows 上搭建gitblit

    https://www.cnblogs.com/ucos/p/3924720.htmlhttps://www.cnblogs.com/sumuncle/p/6362697.htmlhttp://www ...