直做数据库,最近花了点时间把自己常用的东西封装在一起。

DBHelper
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Reflection; namespace DBHelper
{
public sealed class DB : IDisposable
{
#region 数据库类型枚举
/// <summary>
/// 数据库类型
/// </summary>
public enum DBType
{
SQLSERVER,
MDB,
SQLITE
}
#endregion #region 公共成员
public string ConnectionString { get; set; } //连接字符串 DBType _DbType; public DBType DbType
{
get { return this._DbType; }
set
{
this._DbType = value;
switch (value)
{
case DBType.SQLSERVER:
Factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
break;
case DBType.MDB:
Factory = DbProviderFactories.GetFactory("System.Data.OleDb");
break;
case DBType.SQLITE:
Factory = DbProviderFactories.GetFactory("System.Data.SQLite");
break;
}
}
} //数据库类型 public string CommandText { get; set; } //查询语句 //public DbParameterCollection Parameters { get; set; } //参数集合 #endregion #region 私有成员 private DbParameterCollection Parameters { get; set; } //参数集合 #endregion #region 初始成员 private DbConnection Conn = null; //连接对象 private DbProviderFactory Factory = null; //数据库工厂 private List<myTran> TranList = new List<myTran>(); //事务集合 #endregion #region 构造函数
public DB()
{ } public DB(DBType dbType, string connectionString)
{
this.DbType = dbType;
this.ConnectionString = connectionString;
this.Parameters = Factory.CreateCommand().Parameters;
}
#endregion #region 初始化与自动释放 public void Open()
{
try
{
if (Conn == null)
{
Conn = Factory.CreateConnection();
Conn.ConnectionString = this.ConnectionString;
Conn.Open();
}
else
{
if (Conn.State == ConnectionState.Closed)
Conn.Open();
}
}
catch (Exception)
{
throw;
}
} public void Close()
{
try
{
if (Conn.State == ConnectionState.Open)
Conn.Close();
}
catch (Exception)
{
throw;
}
} public void Dispose()
{
try
{
if (Conn.State == ConnectionState.Open)
Conn.Close();
}
catch (Exception)
{
throw;
}
}
#endregion #region 添加查询参数
public void AddParameter(string name, object value)
{
var pa = Factory.CreateParameter();
pa.ParameterName = name;
pa.Value = value;
this.Parameters.Add(pa);
} public void AddParameters<T>(T model) where T : class,new()
{
Type t = typeof(T);
Array.ForEach<System.Reflection.PropertyInfo>(t.GetProperties(), p =>
{
AddParameter("@" + p.Name, p.GetValue(model, null));
});
} public void AddParameters(string[] names, object[] values)
{
if (names.Length != values.Length)
throw new Exception("参数名称跟参数值数量不匹配!");
for (var i = ; i < names.Length; i++)
{
var pa = Factory.CreateParameter();
pa.ParameterName = names[i];
pa.Value = values[i];
this.Parameters.Add(pa);
}
}
#endregion #region 创建查询参数
public DbParameter CreateParameter(string name, object value)
{
var pa = Factory.CreateParameter();
pa.ParameterName = name;
pa.Value = value;
return pa;
} public List<DbParameter> CreateParameters(string[] names, object[] values)
{
if (names.Length != values.Length)
throw new Exception("参数名称跟参数值数量不匹配!");
var parameters = new List<DbParameter>();
for (var i = ; i < names.Length; i++)
{
parameters.Add(CreateParameter(names[i],values[i]));
}
return parameters;
} public List<DbParameter> CreateParameters<T>(T model) where T : class,new()
{
var parameters = new List<DbParameter>();
Type t = typeof(T);
Array.ForEach<System.Reflection.PropertyInfo>(t.GetProperties(), p =>
{
parameters.Add(CreateParameter(p.Name, p.GetValue(model, null)));
});
return parameters;
}
#endregion #region 清除查询字符串和查询参数
/// <summary>
/// 清除查询字符串和查询参数
/// </summary>
void Clear()
{
this.CommandText = "";
if (this.Parameters != null)
this.Parameters.Clear();
}
#endregion #region 返回一个DataTable
/// <summary>
/// 返回一个DataTable
/// </summary>
public DataTable ExecuteDataTable()
{
try
{
using (DbCommand cmd = Factory.CreateCommand())
{
Open();
cmd.Connection = this.Conn;
cmd.CommandText = this.CommandText;
//cmd.Parameters.AddRange(this.Parameters);
if (this.Parameters != null)
foreach (var para in this.Parameters)
{
var p = cmd.CreateParameter();
p.ParameterName = (para as DbParameter).ParameterName;
p.Value = (para as DbParameter).Value;
cmd.Parameters.Add(p);
}
Clear(); DbDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
}
catch (Exception)
{
throw;
}
finally
{
Clear();
}
}
#endregion #region 执行一条更新语句
/// <summary>
/// 执行一条更新语句
/// </summary>
public int ExecuteNonQuery()
{
try
{
using (DbCommand cmd = Factory.CreateCommand())
{
Open();
cmd.Connection = this.Conn;
cmd.CommandText = this.CommandText;
if (this.Parameters != null)
foreach (var para in this.Parameters)
{
var p = cmd.CreateParameter();
p.ParameterName = (para as DbParameter).ParameterName;
p.Value = (para as DbParameter).Value;
cmd.Parameters.Add(p);
}
Clear();
if (this.Conn.State == ConnectionState.Closed)
Open();
return cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
throw;
}
finally
{
Clear();
}
}
#endregion #region 返回首行首列
public object ExecuteScalar()
{
try
{
using (var cmd = Factory.CreateCommand())
{
Open();
cmd.Connection = this.Conn;
cmd.CommandText = this.CommandText;
if (this.Parameters != null)
foreach (var para in this.Parameters)
{
var p = cmd.CreateParameter();
p.ParameterName = (para as DbParameter).ParameterName;
p.Value = (para as DbParameter).Value;
cmd.Parameters.Add(p);
}
Clear();
if (this.Conn.State == ConnectionState.Closed)
Open();
return cmd.ExecuteScalar();
}
}
catch (Exception)
{
throw;
}
finally
{
Clear();
}
}
#endregion #region 自定义事务类
class myTran
{
public string queryString { get; set; }
public List<DbParameter> parameters { get; set; } public myTran(string queryString, List<DbParameter> parameters)
{
this.queryString = queryString;
this.parameters = parameters;
}
}
#endregion #region 添加事务
public void AddTran(string queryString, List<DbParameter> parameters)
{
var tran = new myTran(queryString, parameters);
TranList.Add(tran);
} public void AddTran(string queryString, DbParameter parameter)
{
List<DbParameter> paras = new List<DbParameter>();
if (parameter != null)
paras.Add(parameter);
var tran = new myTran(queryString, paras);
TranList.Add(tran);
}
#endregion #region 清除事务
void ClearTran()
{
TranList.Clear();
}
#endregion #region 执行事务
public void ExecuteTran()
{
try
{
using (DbTransaction tran = Conn.BeginTransaction())
{
try
{
if (this.Conn.State == ConnectionState.Closed)
Open();
TranList.ForEach(m =>
{
using (var cmd = this.Factory.CreateCommand())
{
cmd.Connection = this.Conn;
cmd.CommandText = m.queryString;
cmd.Transaction = tran;
m.parameters.ForEach(n =>
{
cmd.Parameters.Add(n);
});
cmd.ExecuteNonQuery();
}
});
tran.Commit();
}
catch (Exception)
{
tran.Rollback();
throw;
}
finally
{
ClearTran();
}
}
}
catch (Exception)
{
throw;
}
finally
{
ClearTran();
}
}
#endregion #region 根据对象生成更新语句
/// <summary>
/// 获取更新语句
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="Result"></param>
/// <param name="TableName"></param>
/// <param name="IndexFieldName"></param>
/// <returns></returns>
public string GetUpdateString<TResult>(string TableName, string IndexFieldName) where TResult : class,new()
{
string rt = "update " + TableName + " set";
Type t = typeof(TResult);
Array.ForEach<System.Reflection.PropertyInfo>(t.GetProperties(), p =>
{
if (p.Name != IndexFieldName) rt += " " + p.Name + " = @" + p.Name + " ,";
});
rt = rt.Substring(, rt.Length - );
if (IndexFieldName != null)
rt += " where " + IndexFieldName + " = @" + IndexFieldName;
return rt;
}
#endregion #region 根据对象生成插入语句
/// <summary>
/// 获取插入语句
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="Result"></param>
/// <param name="TableName"></param>
/// <param name="IndexFieldName"></param>
/// <returns></returns>
public string GetInsertString<TResult>(string TableName, string IndexFieldName) where TResult : class,new()
{
string rt = "insert into " + TableName + " (";
Type t = typeof(TResult);
Array.ForEach<System.Reflection.PropertyInfo>(t.GetProperties(), p =>
{
if (p.Name != IndexFieldName) rt += p.Name + " , ";
});
rt = rt.Substring(, rt.Length - );
rt += ") values (";
Array.ForEach<System.Reflection.PropertyInfo>(t.GetProperties(), p =>
{
if (p.Name != IndexFieldName)
rt += "@" + p.Name + " , ";
});
rt = rt.Substring(, rt.Length - );
rt += ")";
return rt;
}
#endregion #region 对象操作
/// <summary>
/// 将对象插入到数据库
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="model">对象</param>
/// <param name="TableName">表名</param>
/// <param name="IndexFieldName">主键ID</param>
/// <returns></returns>
public bool InsertModel<T>(T model, string TableName, string IndexFieldName) where T : class,new()
{
this.CommandText = GetInsertString<T>(TableName, IndexFieldName);
this.AddParameters<T>(model);
return this.ExecuteNonQuery() > ;
} /// <summary>
/// 将对象更新到数据库
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="model">对象</param>
/// <param name="TableName">表名</param>
/// <param name="IndexFieldName">主键ID</param>
/// <returns></returns>
public bool UpdateModel<T>(T model, string TableName, string IndexFieldName) where T : class,new()
{
this.CommandText = GetUpdateString<T>(TableName, IndexFieldName);
this.AddParameters<T>(model);
return this.ExecuteNonQuery() > ;
}
#endregion #region 数据库静态方法 #region 生成查询字符串
/// <summary>
/// 返回SQLSERVER连接字符串
/// </summary>
/// <param name="serverIp">服务器IP</param>
/// <param name="uid">用户名</param>
/// <param name="pwd">密码</param>
/// <param name="catalog">库名</param>
/// <param name="timeout">超时时间</param>
/// <returns></returns>
public static string GetSQLConnectionString(string serverIp, string uid, string pwd, string catalog, int timeout)
{
return string.Format("Server={0};User ID={1};PWD={2};Initial Catalog={3};Connect TimeOut={4};", serverIp, uid, pwd, catalog, timeout.ToString());
} /// <summary>
/// 返回Mdb连接字符串
/// </summary>
/// <param name="filePath">数据库路径</param>
/// <param name="password">数据库密码</param>
/// <returns></returns>
public static string GetMdbConnectionString(string filePath, string password)
{
return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=False;Jet OLEDB:Database Password={1}", filePath, password);
} /// <summary>
/// 返回SQLite连接字符串
/// </summary>
/// <param name="filePath">数据库路径</param>
/// <returns></returns>
public static string GetSQLiteConnectionString(string filePath)
{
return string.Format("Data Source={0}", filePath);
}
#endregion #endregion
}
}

使用例1:

/// <summary>
/// 添加内容
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Insert(Model.ContentTable model)
{
using (var db = Program.GetDB())
{
try
{
return db.InsertModel<Model.ContentTable>(model, "ContentTable", "ID");
}
catch (Exception)
{
throw;
}
}
}

使用例2:

/// <summary>
/// 修改内容
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Update(Model.ContentTable model)
{
using (var db = Program.GetDB())
{
try
{
return db.UpdateModel<Model.ContentTable>(model, "ContentTable", "ID");
}
catch (Exception)
{
throw;
}
}
}

使用例3:

/// <summary>
/// 批量插入数据
/// </summary>
/// <param name="lst"></param>
public void InsertAll(List<Model.ContentTable> lst)
{
using (var db = Program.GetDB())
{
try
{
foreach(var model in lst)
{
var names = new string[] {
"Title",
"Content"
};
var values = new object[]{
model.Title,
model.Content
};
db.AddTran(DB.GetInsertString<Model.ContentTable>("ContentTable", "ID"), db.CreateParameters(names, values));
}
db.ExecuteTran();
}
catch (Exception)
{
throw;
}
}
}

Dll文件:这里

Android DB类,支持MDB,SQLITE,SQLSERVER,支持查询、事务,对象直接插入和更新操作等的更多相关文章

  1. SQLServer分页查询方法整理以及批量插入操作SqlBulkCopy

    分页查询 通用方法:sqlserver 2005 + ROW_NUMBER() OVER()方式: ; TOP NOT IN方式 : ID FROM TripDetail ORDER BY ID) O ...

  2. 给JFinal添加 Sqlite 数据库支持

    [转自] http://my.oschina.net/u/237078/blog/69934 Sqlite 的单文件便携性.高性能在开发中方便性无与伦比,即使部署在中小型应用中也胜任有余. 在JFin ...

  3. 实体类的枚举属性--原来支持枚举类型这么简单,没有EF5.0也可以

    通常,我们都是在业务层和界面层使用枚举类型,这能够为我们编程带来便利,但在数据访问层,不使用枚举类型,因为很多数据库都不支持,比如我们现在用的SqlServer2008就不支持枚举类型的列,用的时候也 ...

  4. Android - 支持不同的设备 - 支持不同的平台版本

    在最新版本的Android为app提供很好的新API时,也应该继续支持旧版本的Android直到大部分设备已经更新了.这里将要介绍如何在使用最新API带来的优点的同时继续支持老版本. Dashboar ...

  5. Android - 支持不同的设备 - 支持不同的屏幕

    Android整体上按照两大类来分类设备屏幕:尺寸和分辨率.app在设备上运行应该考虑大小和分辨率.同样的,你应该包含不同的资源来让app适应不同的屏幕大小和分辨率. 整体上有四种尺寸:小的,正常的, ...

  6. .NET+Sqlite如何支持加密

    .NET+Sqlite如何支持加密 Sqlite SQLite 来源于公共领域 SQLite Is Public Domain. 确保代码不会受到任何专有或许可内容的污染,没有任何来自互联网上的未知来 ...

  7. Android - 支持不同的设备 - 支持不同的语言

    把app的字符串放到另外一个文件中是一个好习惯.Android用android工程中的资源文件夹让这件事变的很简单. 如果使用Android SDK Tools创建工程,这个工具会在工程的根目录下创建 ...

  8. 【Android】快速开发偷懒必备(二) 支持DataBinding啦~爽炸,一行实现花式列表[申明:来源于网络]

    [Android]快速开发偷懒必备(二) 支持DataBinding啦~爽炸,一行实现花式列表[申明:来源于网络] 地址:http://blog.csdn.net/zxt0601/article/de ...

  9. databinding在android studio2.3版本后不再默认支持使用

    databinding在android studio2.3版本后不再默认支持使用,需要在项目的app-build-gradle的 dependencies 里面添加 apt 'com.android. ...

随机推荐

  1. 接口自动化之unittest初探

    最近几天苦心钻研unittest,终于略有所得,所以想来跟大家分享一下.有关python和unittest的基础知识部分就不在一一细说,相信各位也不是小白了.如果需要我整理基础知识,欢迎留言,我会看情 ...

  2. [转] docker 部署 odoo

    [From] https://blog.csdn.net/qq_36178641/article/details/79775153 1.安装大象数据库. docker run -d -e POSTGR ...

  3. js toFixed 方法重写,兼容负数

    Number.prototype.toFixed = function (s) { var that = this, changenum, index; if (this < 0) { that ...

  4. SpringBoot集成WebSocket【基于纯H5】进行点对点[一对一]和广播[一对多]实时推送

    代码全部复制,仅供自己学习用 1.环境搭建 因为在上一篇基于STOMP协议实现的WebSocket里已经有大概介绍过Web的基本情况了,所以在这篇就不多说了,我们直接进入正题吧,在SpringBoot ...

  5. 关于:Mac下IDEA更换Maven仓库

    一.MAC安装配置maven环境变量 1.下载maven包: 下载链接:

  6. JMeterPlugins插件

    一.线程组1.jp@gc - Stepping Thread Group,如下图: 类似loadrunner的场景设置,解释:This Group will start 10 threads:这次的测 ...

  7. fastclick源码分析

    https://www.cnblogs.com/diver-blogs/p/5657323.html  地址 fastclick.js源码解读分析 阅读优秀的js插件和库源码,可以加深我们对web开发 ...

  8. user agent stylesheet -- 浏览器默认样式

    user agent stylesheet 从字面意义上很容易理解他表示用户浏览器的样式表. 今天在做项目时,无意间发现一个元素我并没有设置li的text-align:center : 但其中的img ...

  9. Python+selenium实现登录脚本

    import unittestfrom selenium import webdriverfrom time import sleepclass LoginCase(unittest.TestCase ...

  10. MySQL 查询结果分组 group by

    [group by {col_name | position} [ASC | DESC ]] 分组条件 [HAVING where_condition] HAVING 后面的条件必须出现在select ...