SQLite访问封装类

本文介绍了一种使用SQLite作为Windows Mobile平台数据库的方法,并提供了一个SQLiteHelper封装类来简化数据库操作。此外,还针对多线程环境下数据库访问的问题,提出了为不同类型的线程创建独立连接的解决方案。
原文: http://www.cnblogs.com/springtrace/archive/2009/08/31/1557521.html 
SQLite作为windows mobile的数据库,是一种不错的选择。SQLite的下载地址为: SQLite,SQLite的ADO.net Provider下载地址为: System.Data.SQLite ,在发布程序时,请别忘记拷贝SQLite.Interop.065.DLL、system.data.sqlite.dll两个文件到安装目录下。
    本文非原创,而是参考egmkang撰写的  WM下访问SQLite(一种替代SQL CE的解决方案)   ,并根据我自己的编程需要和习惯做了少许修改,错误在所难免。下面实现的是一个SQLiteHelper封装类:
None.gif using  System.Data;
None.gif
using  System.Data.SQLite;
None.gif
using  System.IO;
None.gif
None.gif
namespace  MyHelper.DataAccess
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public class SQLiteHelper
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private static string password = "***";  //请修改***为实际密码
InBlock.gif
        private static string dbFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly()
InBlock.gif            .GetName().CodeBase) 
+ "\\***.db";  //请修改***为实际SQLite数据库名
ExpandedSubBlockStart.gifContractedSubBlock.gif
        private static string connectString = string.Format("Data Source =\"dot.gif{0}\"", dbFilePath, password);
InBlock.gif        
private static SQLiteConnection myConnect = new SQLiteConnection(connectString);
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 取当前SQLite连接
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns>当前SQLite连接</returns> 

InBlock.gif        public static SQLiteConnection GetConnection()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return myConnect;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 执行SQL语句,返回受影响的行数
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="commandString">SQL语句</param>
InBlock.gif        
/// <param name="parameters">SQL语句参数</param>
ExpandedSubBlockEnd.gif        
/// <returns>受影响的行数</returns> 

InBlock.gif        public static int ExecuteNonQuery(string commandString, params SQLiteParameter[] parameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int result = 0;
InBlock.gif            
using (SQLiteCommand command = new SQLiteCommand())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                PrepareCommand(command, 
null, commandString, parameters);
InBlock.gif                result 
= command.ExecuteNonQuery();
InBlock.gif                command.Parameters.Clear();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return result;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 执行带事务的SQL语句,返回受影响的行数
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="transaction">SQL事务</param>
InBlock.gif        
/// <param name="commandString">SQL语句</param>
InBlock.gif        
/// <param name="parameters">SQL语句参数</param>
ExpandedSubBlockEnd.gif        
/// <returns>受影响的行数</returns> 

InBlock.gif        public static int ExecuteNonQuery(SQLiteTransaction transaction, string commandString,
InBlock.gif            
params SQLiteParameter[] parameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int result = 0;
InBlock.gif            
using (SQLiteCommand command = new SQLiteCommand())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                PrepareCommand(command, transaction, commandString, parameters);
InBlock.gif                result 
= command.ExecuteNonQuery();
InBlock.gif                command.Parameters.Clear();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return result;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 执行查询,并返回结果集的第一行第一列的值,忽略其它所有的行和列
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="commandString">SQL语句</param>
InBlock.gif        
/// <param name="parameters">SQL语句参数</param>
ExpandedSubBlockEnd.gif        
/// <returns>第一行第一列的值</returns>

InBlock.gif        public static object ExecuteScalar(string commandString, params SQLiteParameter[] parameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
object result;
InBlock.gif            
using (SQLiteCommand command = new SQLiteCommand())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                PrepareCommand(command, 
null, commandString, parameters);
InBlock.gif                result 
= command.ExecuteScalar();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return result;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 执行SQL语句,返回结果集的DataReader
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="commandString">SQL语句</param>
InBlock.gif        
/// <param name="parameters">SQL语句参数</param>
ExpandedSubBlockEnd.gif        
/// <returns>结果集的DataReader</returns>

InBlock.gif        public static SQLiteDataReader ExecuteReader(string commandString, params SQLiteParameter[] parameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            SQLiteCommand command 
= new SQLiteCommand();
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                PrepareCommand(command, 
null, commandString, parameters);
InBlock.gif                SQLiteDataReader reader 
= command.ExecuteReader(CommandBehavior.CloseConnection);
InBlock.gif                command.Parameters.Clear();
InBlock.gif                
return reader;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 预处理Command对象,数据库链接,事务,需要执行的对象,参数等的初始化
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="command">Command对象</param>
InBlock.gif        
/// <param name="transaction">transaction对象</param>
InBlock.gif        
/// <param name="commandString">SQL语句</param>
ExpandedSubBlockEnd.gif        
/// <param name="parameters">SQL语句参数</param>

InBlock.gif        private static void PrepareCommand(SQLiteCommand command, SQLiteTransaction transaction,
InBlock.gif            
string commandString, params SQLiteParameter[] parameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (myConnect.State != ConnectionState.Open)
InBlock.gif                myConnect.Open();
InBlock.gif
InBlock.gif            command.Connection 
= myConnect;
InBlock.gif            command.CommandText 
= commandString;
InBlock.gif
InBlock.gif            
if (transaction != null)
InBlock.gif                command.Transaction 
= transaction;
InBlock.gif            
if (parameters != null && parameters.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                command.Parameters.AddRange(parameters);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


    为了提高效率,我将数据库连接修改为长连接。这样,只有第一次连接时会比较耗时,以后的操作就比较快了。如果本文有错误的地方,请大家参考egmkang原文。

 

============================================================================================
我的项目中由于是多线程同时操作数据库,我为每个线程都开一个连接.这是我的访问类,如果有问题,大家可以一起讨论:
ContractedBlock.gif ExpandedBlockStart.gif 代码

     
using System;
using System.Data;
using System.Data.SQLite;
using System.Xml;
using System.Collections;

namespace IPass.Utility
{
/// <summary>
/// 数据库的通用访问代码
/// 此类是抽象类,不允许实例化,应用时直接调用即可
/// </summary>
public abstract class SqliteHelper
{
#region 变量声明

private static readonly string connString; // 数据库连接字符串
private static SQLiteConnection SyncConnection; // 同步线程连接
private static SQLiteConnection BizConnection; // 业务线程连接

#endregion

#region 构造函数

static SqliteHelper()
{
string configPath = System.IO.Path.
GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
+ " \\AppConfig.xml " ;
XmlDocument docConfig
= new XmlDocument();
docConfig.Load(configPath);
XmlNode dalNode
= docConfig.SelectSingleNode( " //Config//DbName " );
string dbName = dalNode.InnerText;
string dbDirectoryPath = System.IO.Path.
GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

connString
= string .Format( " Data Source={0}\\{1};Pooling=true;FailIfMissing=false " , dbDirectoryPath, dbName);

SyncConnection
= new SQLiteConnection(connString);
BizConnection
= new SQLiteConnection(connString);

}

#endregion

#region 共用方法
/// <summary>
/// 得到同步数据线程的数据库连接
/// </summary>
/// <returns></returns>
public static SQLiteConnection GetConnection(ConnectionType type)
{
SQLiteConnection conn
= null ;
switch (type)
{
case ConnectionType.Sync:
conn
= SyncConnection;
break ;
case ConnectionType.Biz:
conn
= BizConnection;
break ;
default :
break ;
}
return conn;
}

/// <summary>
/// 执行SqlCommand返回受影响的行数
/// 提供参数
/// </summary>
/// <param > 一个连接字符串 </param>
/// <param > 命令类型(存储过程,或者一个SQL命令.) </param>
/// <param > 存储过程名字,或者是一个SQL语句 </param>
/// <param > 执行命令的参数数组 </param>
/// <returns> 受影响的行数 </returns>
public static int ExecuteNonQuery(CommandType cmdType, ConnectionType type, string cmdText, params SQLiteParameter[] cmdParms)
{
SQLiteConnection conn
= GetConnection(type);
if (conn.State == ConnectionState.Closed)
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction())
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, conn, trans, cmdType, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
// 清除cmd的参数
cmd.Parameters.Clear();
trans.Commit();
return val;
}
catch (System.Data.SQLite.SQLiteException e)
{
trans.Rollback();
conn.Close();
throw new Exception(e.Message);
}
}
}

}


/// <summary>
/// 执行一条返回结果集的SqlCommand命令
/// 提供参数数组
/// </summary>
/// <param > 一个有效字符串 </param>
/// <param > 命令类型(存储过程,或者一个SQL命令.) </param>
/// <param > 存储过程名字,或者是一个SQL语句 </param>
/// <param > 执行命令的参数数组 </param>
/// <returns> SQLiteDataReader </returns>
public static SQLiteDataReader ExecuteReader(CommandType cmdType, ConnectionType type, string cmdText,
params SQLiteParameter[] cmdParms)
{
SQLiteConnection conn
= GetConnection(type);
if (conn.State == ConnectionState.Closed)
conn.Open();

using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, conn,
null , cmdType, cmdText, cmdParms);
SQLiteDataReader rdr
= cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch (System.Data.SQLite.SQLiteException e)
{
conn.Close();
throw new Exception(e.Message);
}
}

}

/// <summary>
/// 执行sql命令,返回首行首列
/// 提供参数数组
/// </summary>
/// <param > 一个有效字符串 </param>
/// <param > 命令类型(存储过程,或者一个SQL命令.) </param>
/// <param > 存储过程名字,或者是一个SQL语句 </param>
/// <param > 执行命令的参数数组 </param>
/// <returns> 一个object类型,可以进行转换 </returns>
public static object ExecuteScalar(CommandType cmdType, ConnectionType type, string cmdText,
params SQLiteParameter[] cmdParms)
{
SQLiteConnection conn
= GetConnection(type);
if (conn.State == ConnectionState.Closed)
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction())
{
using (SQLiteCommand cmd = new SQLiteCommand())
{

try
{
PrepareCommand(cmd, conn,
null , cmdType, cmdText, cmdParms);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
catch (System.Data.SQLite.SQLiteException e)
{
trans.Rollback();
conn.Close();
throw new Exception(e.Message);
}

}
}
}



/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList"> SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[]) </param>
public static void ExecuteSqlTran(Hashtable SQLStringList, ConnectionType type)
{
SQLiteConnection conn
= GetConnection(type);
if (conn.State == ConnectionState.Closed)
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction())
{
SQLiteCommand cmd
= new SQLiteCommand();
try
{
// 循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SQLiteParameter[] cmdParms
= (SQLiteParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, CommandType.Text, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();

trans.Commit();
}
}
catch (System.Data.SQLite.SQLiteException e)
{
trans.Rollback();
conn.Close();
throw new Exception(e.Message);
}
}

}


/// <summary>
/// 为执行命令做参数准备
/// </summary>
/// <param > SqlCommand object </param>
/// <param > SqlConnection object </param>
/// <param > SqlTransaction object </param>
/// <param > 一个存储过程,或者sql语句类型 </param>
/// <param > 一个命令sql语句 </param>
/// <param > 参数集合 </param>
public static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, CommandType cmdType,
string cmdText, SQLiteParameter[] cmdParms)
{
try
{
// 判断连接的状态。如果是关闭状态,则打开
if (conn.State != ConnectionState.Open)
conn.Open();
// cmd属性赋值
cmd.Connection = conn;
cmd.CommandText
= cmdText;
// 是否需要用到事务处理
if (trans != null )
cmd.Transaction
= trans;

cmd.CommandType
= cmdType;
// 添加cmd需要的存储过程参数
if (cmdParms != null )
{
foreach (SQLiteParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}

#endregion
}

#region 枚举
public enum ConnectionType
{
Sync,
// 同步线程的数据库连接
Biz // 业务线程的数据库连接
}
#endregion
}

 

 

转载于:https://www.cnblogs.com/shineqiujuan/archive/2010/01/06/1640214.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值