C# SQLiteHelper

public class SQLiteHelper
{
   private static Lazy<SQLiteHelper> _instance = new Lazy<SQLiteHelper>(() => new SQLiteHelper());
   public static SQLiteHelper Instance = _instance.Value;

 private readonly object queryLockObj = new object();
 public string dbPath;
 public SQLiteConnection sqliteConn;
 public string MinuteData = "DbDatas";

 private SQLiteHelper()
 {
     dbPath = System.AppDomain.CurrentDomain.BaseDirectory + "data.db";
 }

 /// <summary>
 /// 创建数据库
 /// </summary>
 /// <param name="DbFilePath"></param>
 public bool CreateDataBaseFile()
 {
     try
     {
         if (!File.Exists(dbPath))
         {
             SQLiteConnection.CreateFile(dbPath);
         }
         sqliteConn = new SQLiteConnection("data source=" + System.AppDomain.CurrentDomain.BaseDirectory + "data.db");
         return true;
     }
     catch (Exception ex)
     {
         throw new Exception("新建数据库文件" + dbPath + "失败:" + ex.Message);
     }
 }
 /// <summary>
 /// 判断表是否存在
 /// </summary>
 /// <param name="tableName"></param>
 /// <returns></returns>
 public bool TableExist(string table)
 {
     if (sqliteConn.State == ConnectionState.Closed) sqliteConn.Open();
     SQLiteCommand mDbCmd = sqliteConn.CreateCommand();
     mDbCmd.CommandText = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + table + "';";
     int row = Convert.ToInt32(mDbCmd.ExecuteScalar());
     sqliteConn.Close();
     if (0 < row)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
 /// <summary>
 /// 创建表
 /// </summary>
 /// <param name="dbPath">指定数据库文件</param>
 /// <param name="tableName">表名称</param>
 public void CreateTable(string table, List<string> Columns)
 {
     if (sqliteConn.State != System.Data.ConnectionState.Open) sqliteConn.Open();
     string Column = "";
     for (int i = 0; i < Columns.Count; i++)
     {
         Column += Columns[i] + ",";
     }
     Column = Column.Substring(0, Column.Length - 1);
     var cmd = new SQLiteCommand
     {
         Connection = sqliteConn,
         CommandText = " CREATE TABLE " + table + "(" + Column + ")"
     };
     cmd.ExecuteNonQuery();
     sqliteConn.Close();
 }
 /// <summary>
 /// 添加字段
 /// </summary>
 /// <param name="Colms"></param>
 public void CreateColunm(string table, List<string> Colms)
 {
     if (sqliteConn.State != System.Data.ConnectionState.Open) sqliteConn.Open();
     SQLiteCommand cmd = new SQLiteCommand();
     var sql = "select sql from sqlite_master where tbl_name='" + table + "' and type='table';";
     cmd.Connection = sqliteConn;
     cmd.CommandText = sql;
     var com = cmd.ExecuteScalar();
     for (var i = 0; i < Colms.Count; i++)
     {
         try
         {
             if (!com.ToString().Contains(Colms[i]))
             {
                 var sql2 = "alter table " + table + " add column " + Colms[i] + ";";
                 cmd.Connection = sqliteConn;
                 cmd.CommandText = sql2;
                 cmd.ExecuteScalar();
             }
         }
         catch (Exception ex)
         {
             Log.Error("新增字段{0}失败" + ex.Message + Colms[i]);
         }
     }
     sqliteConn.Close();
 }
 /// <summary>
 /// 获取类的属性名称和类型
 /// </summary>
 /// <typeparam name="T">类</typeparam>
 /// <param name="model"></param>
 /// <returns></returns>
 public List<string> GetColumns<T>(T model) where T : class
 {
     List<string> Columns = new List<string>();
     System.Reflection.PropertyInfo[] properties = model.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
     if (properties.Length <= 0)
     {
         throw new Exception("类属性长度为零");
     }
     foreach (System.Reflection.PropertyInfo item in properties)
     {
         string Name;
         if (item.Name != "ID")
         {
             if (item.PropertyType.ToString().Contains("DateTime") || item.PropertyType.ToString().Contains("String"))
             {
                 Name = item.Name + " " + " varchar(100) default NULL";
             }
             else
             {
                 Name = item.Name + " " + item.PropertyType.ToString().Split('.').Last().Replace("]", "") + "(12, 4) default NULL";
             }
         }
         else
         {
             Name = item.Name + "  integer PRIMARY KEY autoincrement";
         }
         Columns.Add(Name);
     }
     return Columns;
 }
 /// <summary>
 /// 获取类的属性名称和类型
 /// </summary>
 /// <typeparam name="T">类</typeparam>
 /// <param name="model"></param>
 /// <returns></returns>
 public List<string> GetColumns(List<string> cols)
 {
     var Columns = new List<string>
     {
         "ID  integer PRIMARY KEY autoincrement",
         "Dbtime  varchar(100) default NULL",
         "Status integer default 0",
         "SpecMax integer default NULL"
     };
     foreach (string item in cols)
     {
         string Name = item + " decimal(10, 4) default NULL";
         Columns.Add(Name);
     }
     return Columns;
 }

 public string[] GetKeys<T>(T model) where T : class
 {
     System.Reflection.PropertyInfo[] properties = model.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
     if (properties.Length <= 0)
     {
         throw new Exception("类属性长度为零");
     }
     string[] Columns = new string[properties.Length - 1];
     int con = 0;
     foreach (System.Reflection.PropertyInfo item in properties)
     {
         if (item.Name != "ID")
         {
             Columns[con++] = item.Name;
         }
     }
     return Columns;
 }
 public string AddString(string TableName, string[] keys, string[] values)
 {
     string keys_string = "(" + keys[0];
     string value_string = "('" + values[0] + "'";

     for (int i = 1; i < keys.Length; i++)
     {
         keys_string += "," + keys[i];
     }
     for (int i = 1; i < values.Length; i++)
     {
         value_string += ",'" + values[i] + "'";
     }
     keys_string += ")";
     value_string += ")";
     string sql = string.Format("INSERT INTO " + TableName + " {0} VALUES {1} ;", keys_string, value_string);
     return sql;
 }
 public string AddString(string TableName, Dictionary<string, string> keyValues)
 {
     string keys_string = "( ";
     string value_string = "( ";
     int count = 0;
     foreach (var item in keyValues)
     {
         if (count == 0)
         {
             keys_string += item.Key;
             value_string += "'" + item.Value + "'";
             count++;
         }
         else
         {
             keys_string += "," + item.Key;
             value_string += ",'" + item.Value + "'";
         }
     }
     keys_string += ")";
     value_string += ")";
     string sql = string.Format("INSERT INTO " + TableName + " {0} VALUES {1} ;", keys_string, value_string);
     return sql;
 }

 public string AddStringReal(string TableName, Dictionary<string, decimal> keyValues)
 {
     string keys_string = "( Dbtime ";
     string value_string = "('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
     foreach (var item in keyValues)
     {
         keys_string += "," + item.Key;
         value_string += ",'" + item.Value + "'";
     }
     keys_string += ")";
     value_string += ")";
     string sql = string.Format("INSERT INTO " + TableName + " {0} VALUES {1} ;", keys_string, value_string);
     return sql;
 }

 public int QueryCount(string TableName, string where = "")
 {
     var value = 0;
     try
     {
         lock (queryLockObj)
         {
             using (SQLiteCommand cmd = new SQLiteCommand())
             {
                 if (sqliteConn.State != System.Data.ConnectionState.Open) sqliteConn.Open();
                 cmd.Connection = sqliteConn;
                 cmd.CommandText = " select count(*) from " + TableName + " " + where;
                 SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
                 DataTable dt = new DataTable();
                 da.Fill(dt);
                 sqliteConn.Close();

                 if (int.TryParse(dt.Rows[0][0].ToString(), out var result))
                 {
                     value = result;
                 }
             }
             return value;
         }
     }
     catch (Exception ex)
     {
         Log.Error("查询出错:" + TableName + where + "\r\n" + ex.Message);
     }
     return value;
 }
 public List<T> Query<T>(string TableName, string where = "") where T : new()
 {
     try
     {
         lock (queryLockObj)
         {
             List<T> datas = new List<T>();
             using (SQLiteCommand cmd = new SQLiteCommand())
             {
                 if (sqliteConn.State != System.Data.ConnectionState.Open) sqliteConn.Open();
                 cmd.Connection = sqliteConn;
                 cmd.CommandText = " select * from " + TableName + " " + where;
                 SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
                 DataTable dt = new DataTable();
                 da.Fill(dt);
                 sqliteConn.Close();

                 System.Reflection.PropertyInfo[] properties = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                 if (properties.Length <= 0)
                 {
                     throw new Exception("类属性长度为零");
                 }
                 foreach (DataRow dd in dt.Rows)
                 {
                     int i = 0;
                     var model = new T();
                     foreach (System.Reflection.PropertyInfo item in properties)
                     {
                         var value = dd[i++];
                         if (value is DBNull)
                         {
                             var ds = Convert.ChangeType(0, item.PropertyType);
                             item.SetValue(model, ds, null);
                         }
                         else
                         {
                             var ds = Convert.ChangeType(value, item.PropertyType);
                             item.SetValue(model, ds, null);
                         }
                     }
                     datas.Add(model);
                 }
             }
             return datas;
         }
     }
     catch (Exception ex)
     {
         Log.Error("查询出错:" + TableName + where + "\r\n" + ex.Message);
         return new List<T>();
     }
 }
 public List<T> Query<T>(string sql) where T : new()
 {
     try
     {
         lock (queryLockObj)
         {
             List<T> datas = new List<T>();
             using (SQLiteCommand cmd = new SQLiteCommand())
             {
                 if (sqliteConn.State != System.Data.ConnectionState.Open) sqliteConn.Open();
                 cmd.Connection = sqliteConn;
                 cmd.CommandText = sql;
                 SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
                 DataTable dt = new DataTable();
                 da.Fill(dt);
                 sqliteConn.Close();

                 System.Reflection.PropertyInfo[] properties = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                 if (properties.Length <= 0)
                 {
                     throw new Exception("类属性长度为零");
                 }
                 foreach (DataRow dd in dt.Rows)
                 {
                     int i = 0;
                     var model = new T();
                     foreach (System.Reflection.PropertyInfo item in properties)
                     {
                         var value = dd[i++];
                         if (value is DBNull)
                         {
                             var ds = Convert.ChangeType(0, item.PropertyType);
                             item.SetValue(model, ds, null);
                         }
                         else
                         {
                             var ds = Convert.ChangeType(value, item.PropertyType);
                             item.SetValue(model, ds, null);
                         }
                     }
                     datas.Add(model);
                 }
             }
             return datas;
         }
     }
     catch (Exception ex)
     {
         Log.Error("查询出错:" + sql + "\r\n" + ex.Message);
         return new List<T>();
     }
 }

 private readonly object LockObj = new object();
 public bool SqliteDbTransaction(string sqlString)
 {
     lock (LockObj)
     {
         if (sqliteConn.State == ConnectionState.Closed) sqliteConn.Open();
         DbTransaction trans = sqliteConn.BeginTransaction();
         try
         {
             using (SQLiteCommand cmd = new SQLiteCommand(sqliteConn))
             {
                 int rows = 0;
                 cmd.CommandText = sqlString;
                 rows = cmd.ExecuteNonQuery();
                 trans.Commit();//提交事务
                 sqliteConn.Close();
                 return rows > 0;
             }
         }
         catch (Exception ex)
         {
             trans.Rollback();//回滚事务
             sqliteConn.Close();
             Log.Error("提交数据库失败" + ex.Message);
             return false;
         }
     }
 }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容