//--------------------------日期:2014-2-22 //--------------------------版本:2.0.2.0 //--------------------------作者:itrycn using System; using System.Data; using System.Data.SQLite; //数据库操作类 namespace ryCommonDb { /// /// /// public class ClsDb { /// /// /// public ClsDb() { } /// /// /// ~ClsDb() { CloseDb(); } /// /// /// /// 数据库路径 /// 数据库密码 /// public ClsDb(string DbFilePath, string PassWord) { DbPath = DbFilePath; DbPassWord = PassWord; } /// /// /// /// 数据库路径 /// public ClsDb(string DbFilePath) { DbPath = DbFilePath; } /// /// /// public SQLiteConnection SQLite_cn; /// /// /// public string DbPath = ""; /// /// /// public string DbPassWord = ""; /// /// 连接数据库 /// /// public int ConnDb() { try { string folderPath = System.IO.Path.GetDirectoryName(DbPath); if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); } string connstr = string.Format("Data Source={0}", DbPath); SQLite_cn = new SQLiteConnection(connstr); SQLite_cn.SetPassword(DbPassWord); SQLite_cn.Open(); return 1; } catch { return -1; } } /// /// 设置路径和密码 /// /// public int SetPathPwd(string Path, string PassWord) { DbPath = Path; DbPassWord = PassWord; return 1; } /// /// 连接数据库 /// /// public int ConnDb(string Path, string PassWord) { try { DbPath = Path; string folderPath = System.IO.Path.GetDirectoryName(DbPath); if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); } DbPassWord = PassWord; string connstr = string.Format("Data Source={0}", DbPath); SQLite_cn = new SQLiteConnection(connstr); SQLite_cn.SetPassword(DbPassWord); SQLite_cn.Open(); DataTable schemaTable = SQLite_cn.GetSchema("TABLES"); return SQLite_cn.State==ConnectionState.Open?1:0; } catch(Exception) { return -1; } } /// /// /// /// public void ChangePwd(string newPwd) { SQLite_cn.ChangePassword(newPwd); } /// /// 连接或创建数据库,如果数据库不存在,就创建,否则连接 /// /// public int ConnOrCreateDb() { try { string folderPath = System.IO.Path.GetDirectoryName(DbPath); if (System.IO.File.Exists(DbPath) == false) { if (System.IO.Directory.Exists(folderPath) == false) { System.IO.Directory.CreateDirectory(folderPath); } if (System.IO.Directory.Exists(folderPath) == false) { return -1; } else { CreateDbByExample(); return 1; } } else { ConnDb(); return 1; } } catch { return -2; } } /// /// 连接或创建数据库,如果数据库不存在,就创建,否则连接 /// /// public int ConnOrCreateDb(string Path,string PassWord) { try { DbPath = Path; DbPassWord = PassWord; string folderPath = System.IO.Path.GetDirectoryName(DbPath); if (System.IO.File.Exists(DbPath) == false) { if (System.IO.Directory.Exists(folderPath) == false) { System.IO.Directory.CreateDirectory(folderPath); } if (System.IO.Directory.Exists(folderPath) == false) { return -1; } else { CreateDbByExample(); return 1; } } else { ConnDb(); return 1; } } catch { return -2; } } /// /// 关闭数据库 /// /// public void CloseDb() { try { if (SQLite_cn!=null && SQLite_cn.State != ConnectionState.Closed) { SQLite_cn.Close(); } } catch { } } /// /// 运行SQL命令 /// /// SQL语句 /// SQL命令参数 /// 运行失败,则返回-1,否则返回影响的行数 public int ExecuteNonQuery(string SQLText, SQLiteParameter[] commandParameters) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; if (commandParameters.Length > 0) { foreach (SQLiteParameter parm in commandParameters) { cm.Parameters.Add(parm); } } cm.Connection = SQLite_cn; int i=cm.ExecuteNonQuery(); cm.Dispose(); return i; } #endregion } catch { return -1; } } /// /// 运行SQL命令 /// /// SQL语句 /// 运行失败,则返回-1,否则返回影响的行数 public int ExecuteNonQuery(string SQLText) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; cm.Connection = SQLite_cn; int i = cm.ExecuteNonQuery(); cm.Dispose(); return i; } #endregion } catch { return -1; } } /// /// 运行SQL命令,并返回结果 /// /// SQL语句 /// SQL命令参数 /// 运行失败,则返回null,否则返回以数组显示的字符串 public string[] ExecuteSQL(string SQLText, SQLiteParameter[] commandParameters) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; if (commandParameters.Length > 0) { cm.Parameters.AddRange(commandParameters); } SQLiteDataReader reader = cm.ExecuteReader(); string[] resultStr=null; while (reader.Read()) { resultStr = new string[reader.FieldCount]; for (int i = 0; i < reader.FieldCount; i++) { resultStr[i] = reader[i].ToString(); } break; } reader.Close(); cm.Dispose(); return resultStr; } #endregion } catch { return null; } } /// /// 运行SQL命令,并返回结果 /// /// SQL语句 /// SQL命令参数 /// 数组第一个默认的值 /// 运行失败,则返回null,否则返回以数组显示的字符串 public string[] ExecuteSQL(string SQLText, SQLiteParameter[] commandParameters, string DefFristValue) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; if (commandParameters.Length > 0) { cm.Parameters.AddRange(commandParameters); } SQLiteDataReader reader = cm.ExecuteReader(); string[] resultStr = null; while (reader.Read()) { resultStr = new string[reader.FieldCount]; for (int i = 0; i < reader.FieldCount; i++) { resultStr[i] = reader[i].ToString(); } break; } if (resultStr == null) { resultStr = new string[1]; resultStr[0] = DefFristValue; } reader.Close(); cm.Dispose(); return resultStr; } #endregion } catch { string[] resultStr = new string[1]; resultStr[0] = DefFristValue; return resultStr; } } /// /// 运行SQL命令,并返回结果 /// /// SQL语句 /// 运行失败,则返回null,否则返回以数组显示的字符串 public string[] ExecuteSQL(string SQLText) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; SQLiteDataReader reader = cm.ExecuteReader(); string[] resultStr = null; while (reader.Read()) { resultStr = new string[reader.FieldCount]; for (int i = 0; i < reader.FieldCount; i++) { resultStr[i] = reader[i].ToString(); } break; } reader.Close(); cm.Dispose(); return resultStr; } #endregion } catch { return null; } } /// /// 运行SQL命令,并返回结果 /// /// SQL语句 /// 数组第一个默认的值 /// 运行失败,则返回DefFristValue,否则返回以数组显示的字符串 public string[] ExecuteSQL(string SQLText,string DefFristValue) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; SQLiteDataReader reader = cm.ExecuteReader(); string[] resultStr = null; while (reader.Read()) { resultStr = new string[reader.FieldCount]; for (int i = 0; i < reader.FieldCount; i++) { resultStr[i] = reader[i].ToString(); } break; } reader.Close(); cm.Dispose(); if (resultStr == null) { resultStr = new string[1]; resultStr[0] = DefFristValue; } return resultStr; } #endregion } catch { string[] resultStr = new string[1]; resultStr[0] = DefFristValue; return resultStr; } } /// /// 清空指定表的所有数据 /// /// 表名 /// 运行失败,则返回-1,否则返回影响的行数 [Obsolete("不建议使用,请使用ClearTableData属性", false)] public int DeleteTable(string TableName) { return ClearTableData(TableName); } /// /// 清空指定表的所有数据 /// /// 表名 /// 运行失败,则返回-1,否则返回影响的行数 public int ClearTableData(string TableName) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = "delete from " + TableName; cm.Connection = SQLite_cn; int i = cm.ExecuteNonQuery(); cm.Dispose(); return i; } #endregion } catch { return -1; } } /// /// 判断指定值是否存在 /// /// 表名 /// 指定值所属字段 /// 指定值 /// 当前id,如果是新增记录,请填写-1 /// public bool IsExistValue(string TableName,string valueField,string value,int curId) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = "select * from " + TableName + " where " + valueField + "=@tvalue"; cm.Parameters.Add("@tvalue", DbType.String); cm.Parameters["@tvalue"].Value = value; SQLiteDataReader reader = cm.ExecuteReader(); bool result = false; while (reader.Read()) { if (curId < 0) { result = true; } else { if (reader["id"].ToString() == curId.ToString()) { result = false; } else { result=true; } } break; } reader.Close(); cm.Dispose(); return result; } #endregion } catch { return false; } } /// /// 判断SQL语句是否有结果返回 /// /// SQL语句 /// SQL命令参数 /// 运行失败,则返回-1;存在结果,返回1;不存在结果,返回0 public int ExecuteReadResult(string SQLText, SQLiteParameter[] commandParameters) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; if (commandParameters.Length > 0) { cm.Parameters.AddRange(commandParameters); //foreach (SQLiteParameter parm in commandParameters) //{ cm.Parameters.Add(parm); } } SQLiteDataReader reader = cm.ExecuteReader(); int i = 0; while (reader.Read()) { i = 1; break; } reader.Close(); cm.Dispose(); return i; } #endregion } catch { return -1; } } /// /// 判断SQL语句是否有结果返回 /// /// SQL语句 /// 运行失败,则返回-1;存在结果,返回1;不存在结果,返回0 public int ExecuteReadResult(string SQLText) { try { #region 数据库 { SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = SQLText; SQLiteDataReader reader = cm.ExecuteReader(); int i = 0; while (reader.Read()) { i = 1; break; } reader.Close(); cm.Dispose(); return i; } #endregion } catch { return -1; } } /// /// 创建数据库 /// /// SQL语句 /// public void CreateDb(string SQLText) { if (SQLite_cn == null) { ConnDb(); } if (SQLite_cn.State != ConnectionState.Open) //如果数据库未打开,则先打开数据库 { ConnDb(); } SQLiteCommand cmd = SQLite_cn.CreateCommand(); cmd.CommandText = SQLText; cmd.ExecuteNonQuery(); cmd.Dispose(); } /// /// 根据内置例子创建数据库 /// /// public void CreateDbByExample() { if (SQLite_cn == null) { ConnDb(); } if (SQLite_cn.State != ConnectionState.Open) //如果数据库未打开,则先打开数据库 { ConnDb(); } SQLiteCommand cmd = SQLite_cn.CreateCommand(); string tmpStr = "([ID] INTEGER PRIMARY KEY,[Name] TEXT COLLATE NOCASE,[sValue1] TEXT COLLATE NOCASE,[sValue2] TEXT COLLATE NOCASE,[TD1] TEXT COLLATE NOCASE, [TD2] TEXT COLLATE NOCASE, [TD3] TEXT COLLATE NOCASE, [TD4] TEXT COLLATE NOCASE, [TD5] TEXT COLLATE NOCASE, [IntData1] INTEGER DEFAULT 0, [IntData2] INTEGER DEFAULT 0, [IntData3] INTEGER DEFAULT 0, [floatData1] FLOAT DEFAULT 0, [floatData2] FLOAT DEFAULT 0, [floatData3] FLOAT DEFAULT 0, [floatData4] FLOAT DEFAULT 0, [floatData5] FLOAT, [date1] DATETIME, [date2] DATETIME, [date3] DATETIME, [date4] DATETIME, [date5] DATETIME);"; for (int i = 1; i < 16; i++) { cmd.CommandText = "CREATE TABLE MainTable"+i.ToString()+" " + tmpStr; cmd.ExecuteNonQuery(); } cmd.Dispose(); } /// /// 保存信息,如果Name不存在,系统会自动创建 /// /// 返回1,表示成功,0表示失败 public int SetSysNameValue(string Name, string Value, string TableName) { try { #region 添加记录到数据库 //try { int haveRecord = 0; SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = "update [" + TableName + "] set sValue1=@sValue1,date2=@date2 where Name=@Name"; cm.Parameters.Add("@Name", DbType.String); cm.Parameters["@Name"].Value = Name; cm.Parameters.Add("@sValue1", DbType.String); cm.Parameters["@sValue1"].Value = Value; cm.Parameters.Add("@date2", DbType.DateTime); cm.Parameters["@date2"].Value = DateTime.Now; cm.Connection = SQLite_cn; haveRecord=cm.ExecuteNonQuery(); cm.Parameters.Clear(); if (haveRecord == 0) { cm.CommandText = "insert into [" + TableName + "] ([Name],[sValue1],[date1],[date2]) values(@Name,@sValue1,@date1,@date1)"; cm.Parameters.Add("@Name", DbType.String); cm.Parameters["@Name"].Value = Name; cm.Parameters.Add("@sValue1", DbType.String); cm.Parameters["@sValue1"].Value = Value; cm.Parameters.Add("@date1", DbType.DateTime); cm.Parameters["@date1"].Value = DateTime.Now; cm.Connection = SQLite_cn; cm.ExecuteNonQuery(); cm.Dispose(); } } //catch { } #endregion return 1; } catch { return 0; } } /// /// 获取信息 /// /// public string GetValueByName(string Name,string TableName,string defValue) { try { #region 从数据库获取记录 //try { string haveRecord = defValue; SQLiteCommand cm = SQLite_cn.CreateCommand(); cm.Parameters.Clear(); cm.CommandText = "select * from " + TableName + " where Name=@Name"; cm.Parameters.Add("@Name", DbType.String); cm.Parameters["@Name"].Value = Name; cm.Connection = SQLite_cn; SQLiteDataReader reader = cm.ExecuteReader(); while (reader.Read()) { haveRecord = reader["sValue1"].ToString(); break; } reader.Close(); cm.Dispose(); return haveRecord; } //catch { } #endregion } catch { return defValue; } } /// /// 获取信息 /// /// public string GetValueByName(string Name, string TableName) { return GetValueByName(Name, TableName,""); } } }