/// <summary> /// 创建一个安全的数据库连接,执行sql指令,回调函数使用参数DataReader处理数据 /// </summary> /// <param name="callBack"></param> public void UsingSafeConnection(SQLiteString sql, Action <SQLiteDataReader> callBack) { using (SQLiteConnection con = new SQLiteConnection(this.DataSource)) { con.Open(); using (SQLiteCommand com = new SQLiteCommand(con)) { try { com.CommandText = sql.SqlText; sql.SetCommand(com); var reader = com.ExecuteReader(); callBack(reader); reader.Close(); } catch (Exception ex) { throw new Exception(string.Format("SQLite数据库[{0}]操作发生异常", this.DataSource), ex); } finally { con.Close(); con.Dispose(); } } } }
/// <summary> /// 执行sql,返回首行首列的值 /// </summary> public string ExecuteScalar(SQLiteString sql) { string result = string.Empty; this.UsingSafeConnection(com => { com.CommandText = sql.SqlText; sql.SetCommand(com); result = com.ExecuteScalar().ToSafeString(); }); return(result); }
/// <summary> /// 执行Sql,返回受影响的行数 /// </summary> public int ExecuteNonQuery(SQLiteString sql) { int result = 0; this.UsingSafeConnection(com => { com.CommandText = sql.SqlText; sql.SetCommand(com); result = com.ExecuteNonQuery(); }); return(result); }
/// <summary> /// 执行sql,获取动态类型数据集合 /// </summary> public List <dynamic> FindByExistingConnection(SQLiteString sql) { List <dynamic> items = new List <dynamic>(); this.UsingExistingConnection(sql, (reader) => { while (reader.Read()) { items.Add(reader.ToDynamic()); } }); return(items); }
public void UsingExistingConnection(SQLiteString sql, Action <SQLiteDataReader> callBack) { using (SQLiteCommand com = new SQLiteCommand(this.ExistingConnection)) { try { com.CommandText = sql.SqlText; sql.SetCommand(com); var reader = com.ExecuteReader(); callBack(reader); } catch (Exception ex) { throw new Exception(string.Format("SQLite数据库[{0}]操作发生异常", this.DataSource), ex); } } }
/// <summary> /// 执行sql,获取动态类型数据集合 /// </summary> public List <dynamic> Find(SQLiteString sql) { try { List <dynamic> items = new List <dynamic>(); this.UsingSafeConnection(sql, (reader) => { while (reader.Read()) { items.Add(reader.ToDynamic()); } }); return(items); } catch { return(new List <dynamic>()); } }