using System; using System.Collections.Generic; using System.Data; using System.Data.SQLite; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JJMediSys { class SQLiteDBHelper { /// /// /// public string connectionString = string.Empty; /// /// /// public SQLiteConnection connection = null; /// /// 构造函数 /// /// 数据库文件路径 public SQLiteDBHelper(string dbPath) { this.connectionString = "Data Source=" + dbPath; } /// /// 创建数据库文件 /// /// public void CreateDB(string dbPath,string CreateSql) { using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(connection)) { bool ret = ExecuteCommand(CreateSql); } } } /// /// 打开连接 /// /// /// public void SetDataSource(string dataSource, string password) { connectionString = string.Format("Data Source={0};Pooling=true;FailIfMissing=false", dataSource); connection = new SQLiteConnection(connectionString); if (!string.IsNullOrEmpty(password)) { //connection.SetPassword(password); } connection.Open(); } #region 通用方法 /// /// 查询表 /// /// /// public DataTable ExecQuery(string sqlStr) { DataTable dt = new DataTable(); try { SQLiteDataAdapter OraDa = new SQLiteDataAdapter(sqlStr, connection); OraDa.Fill(dt); return dt; } catch (SQLiteException e) { string s = e.Message; return null; } } /// /// 增、删、改操作 /// /// sql语句 /// 是否成功 public bool ExecuteCommand(string sqlStr) { using (SQLiteCommand cmd = new SQLiteCommand(sqlStr, connection)) { try { if (cmd.ExecuteNonQuery() > 0) { return true; } else { return false; } } catch (Exception ex) { ex.ToString(); return false; } } } /// /// 根据查询语句,获取表中记录的条数 select count(*) from t_Developer /// /// /// public int GetRecordCount(string sqlStr) { using (SQLiteCommand cmd = new SQLiteCommand(sqlStr, connection)) { try { cmd.CommandText = sqlStr; SQLiteDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { return dr.FieldCount; } return 0; } catch (Exception e) { e.ToString(); return 0; } } } #endregion } }