设为首页 收藏本站
查看: 1133|回复: 0

[经验分享] 操作 sqlite封装的一个类库

[复制链接]

尚未签到

发表于 2016-11-30 09:09:58 | 显示全部楼层 |阅读模式
  在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命令,并返回Read,Read使用完毕,必须关闭
/// </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=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.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 + " )";
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.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
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-307485-1-1.html 上篇帖子: SQLite支持字段类型及建表 下篇帖子: sqlite3: 一个SQLite数据库的命令行接口
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表