操作 sqlite封装的一个类库

   在wince设备上,使用sqlite很方便,基本都能满足项目的需要,速度也不错。在工作中,封装了此类,方便开发。

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.sqlite;
using System.Data;
using System.IO;

namespace Austec.DB
{
public class Csqlite : Idisposable
{
public string m_LastError = null;
private string dbPath = "";
private sqliteConnection sqConn = null;
private sqliteCommand sqCmd = null;
private sqliteTransaction transaction = null;

private bool m_Result = false;
public bool Result
{
get { return m_Result; }
}

/// <summary>
/// 不允许通过该方式构造此类
/// </summary>
private Csqlite(){}

/// <summary>
/// 打开数据库
/// </summary>
/// <param name="dbPath">数据库路径</param>
public Csqlite( string dbPath )
{
this.dbPath = dbPath;
}

~Csqlite()
{
Close();
}

#region 打开与关闭

public bool open()
{
try
{
m_Result = false;

if (sqConn == null)
{
//在打开数据库时,会判断数据库是否存在,如果不存在,则在当前目录下创建一个
sqConn= new sqliteConnection("Data Source=" + dbPath +";Pooling=true;FailIfMissing=false");
sqCmd = new sqliteCommand();
sqCmd.Connection = sqConn;
}

if (sqConn.State == ConnectionState.Closed)
{
bool dbExsit = System.IO.File.Exists(dbPath);
sqConn.open();
/// 如果数据库不存在,sqlite会创建一个空的数据库,在此创建一个无用的表,填充数据库
if (!dbExsit)
{
ExecuteNonQuery("create table Liang ( id nvarchar(1) ) ");
}
}
m_Result = true;
return true;
}
catch (System.Exception ex)
{
m_LastError = ex.Message;
return false;
}
}

public void dispose()
{
Close();
}

public void Close()
{
if (sqConn != null)
{
if (sqConn.State == ConnectionState.Open)
{
sqConn.Close();
sqConn = null;
sqCmd = null;
}
}
System.Data.sqlite.sqliteConnection.ClearallPools();
}

#endregion


/// <summary>
/// 执行不带返回结果的命令
/// </summary>
/// <param name="sqlCmd">查询语句</param>
/// <returns></returns>
public bool ExecuteNonQuery(string sqlCmd )
{
m_LastError = null;
m_Result = false;
try
{
sqCmd.CommandText = sqlCmd;
sqCmd.ExecuteNonQuery();
m_Result = true;
}
catch (System.Exception ex)
{
m_LastError= ex.Message;
return false;
}
return true;
}

/// <summary>
/// 执行sql命令,并返回Read,Read使用完毕,必须关闭
/// </summary>
/// <param name="sqlCmd"></param>
/// <returns></returns>
public sqliteDataReader ExecuteQuery(string sqlCmd)
{
m_LastError = null;
m_Result = false;
try
{
sqCmd.CommandText = sqlCmd;
sqliteDataReader read = sqCmd.ExecuteReader();
m_Result = true;
return read;
}
catch (System.Exception ex)
{
m_LastError = ex.Message;
return null;
}
}

/// <summary>
/// 执行sql命令,必须关闭
/// </summary>
/// <param name="sqlCmd"></param>
/// <returns></returns>
public bool ExecuteQueryTable(string sqlCmd,out DataTable dt)
{
m_LastError = null;
m_Result = false;

dt = new DataTable("liang");

try
{
// 执行查询命令
sqliteDataReader read = ExecuteQuery(sqlCmd);
if ( m_Result)
{
m_Result = false;
if ( read==null )
{
m_LastError = "sqlite error:未查询到数据!";
return false;
}

/// 添充表
for( int i=0; i<read.FieldCount;i++)
{
dt.Columns.Add(new DataColumn(i.ToString()));
}
while (read.Read())
{
DaTarow row= dt.NewRow();
for( int i=0; i<read.FieldCount;i++ )
{
row[i]=read.GetValue(i).ToString();
}
dt.Rows.Add(row);
}
read.Close();
m_Result = true;
return true;
}
return false;
}
catch (System.Exception ex)
{
m_LastError = ex.Message;
return false;
}
}

/// <summary>
/// 执行sql命令,并返回第一行记录的第一列值
/// </summary>
/// <param name="sqlCmd"></param>
/// <returns></returns>
public object ExecuteScalar( string sqlCmd )
{
m_LastError = null;
m_Result = false;
try
{
sqCmd.CommandText = sqlCmd;
object ob= sqCmd.ExecuteScalar();
if ( ob!=null )
{
m_Result = true;
}
else
{
m_LastError = "sqlite error:未查询到数据";

}
return ob;
}
catch (System.Exception ex)
{
m_LastError = ex.Message;
return null;
}
}


/// <summary>
/// 按照内存表的结构创建表及索引;如果表已经存在,将直接返回
/// </summary>
/// <param name="dt">在创建的表</param>
/// <param name="strIndexField">索引字段,多个字段以逗号分隔</param>
/// <returns></returns>
public bool CreateTable(ref DataTable dt,string strIndexField )
{
try
{
m_Result = false;
if ( dt==null )
{
return false;
}
// 查询表有没有存在
string sql = "select count(*) from sqlite_master where tbl_name='" + dt.TableName + "' and type='table'";
object ob = ExecuteScalar(sql);
if (!m_Result)
{
return false;
}
if (Convert.ToInt32(ob) == 1)
{
m_Result = true;
return true;
}

string strsql="",strCmdsql="";

strCmdsql = " CREATE TABLE " + dt.TableName + " ( ";
for (int i = 0; i < dt.Columns.Count; i++ )
{
strsql += dt.Columns[i].ColumnName + " nvarchar(30) ";
if ( i<dt.Columns.Count-1)
{
strsql += ",";
}
}

strCmdsql += strsql + " )";
if (!ExecuteNonQuery(strCmdsql))
{
return false;
}

if ( strIndexField!=null && strIndexField.Trim().Length>0 )
{
string[] strIndex = strIndexField.Split(',');
for (int i = 0; i < strIndex.Length; i++)
{
strCmdsql = "CREATE INDEX " + dt.TableName + "_index" + i.ToString() +" ON " + dt.TableName + " ( " + strIndex[i] + " )";
if (!ExecuteNonQuery(strCmdsql))
{
return false;
}
}
}
m_Result = true;
return true;
}
catch (System.Exception ex)
{
m_LastError = ex.Message;
return false;
}
}


/// <summary>
/// 删除表及表的索引
/// </summary>
/// <param name="tablename"></param>
/// <returns></returns>
public bool DropTableAndindex( string tablename )
{
m_Result = false;
try
{
// 查询表及索引有没有存在
string sql = "select count(*) from sqlite_master where tbl_name='" + tablename + "' and type='table'";
object ob= ExecuteScalar(sql);
if (!m_Result)
{
return false;
}
if ( Convert.ToInt32(ob)==0 )
{
m_Result=true;
return true;
}

string cmdsql = "drop table " + tablename ;
if ( !ExecuteNonQuery(cmdsql) )
{
return false;
}
m_Result = true;
return true;
}
catch (System.Exception ex)
{
m_LastError = ex.Message;
return false;
}
}

/// <summary>
/// 将内存表插入相应的表中
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public bool InsertTable( ref DataTable dt)
{
m_Result = false;
if (dt == null)
{
return false;
}
if ( dt.Rows.Count==0 )
{
m_Result = true;
return true;
}

int i = 0;
string sql = "insert into " + dt.TableName + " values( ";
string sqlData = "",strCmdsql = "";

BeginTransaction();
foreach (DaTarow row in dt.Rows)
{
sqlData = "";
for (i = 0; i < dt.Columns.Count; i++)
{
sqlData += "'" + row[i].ToString() + "'";
if (i < dt.Columns.Count - 1)
{
sqlData += ",";
}
}
strCmdsql = sql + sqlData + " )";
if (!ExecuteNonQuery(strCmdsql))
{
Rollback();
return false;
}
}

Commit();
m_Result = true;
return true;
}

/// <summary>
/// 删除指定表的数据
/// </summary>
/// <param name="tableName">表名</param>
/// <returns></returns>
public bool DeleteTableData( string tableName )
{
m_Result = false;

string sql = "select count(*) from sqlite_master where tbl_name='" + tableName + "' and type='table'";
object ob= ExecuteScalar(sql);
if (!m_Result)
{
return false;
}
m_Result = false;
if ( Convert.ToInt32(ob)==0 )
{
m_LastError = "被删除数据的表不存在!";
return false;
}

sql = "delete from " + tableName;
if ( ExecuteNonQuery(sql) )
{
m_Result = true;
return true;
}
else
{
return false;
}
}

#region 事务操作
public void BeginTransaction()
{
transaction = sqConn.BeginTransaction();
}

public void Commit()
{
transaction.Commit();
}

public void Rollback() { transaction.Rollback(); } #endregion }}

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能