//--------------------------日期:2014-2-22
//--------------------------版本:2.0.2.0
//--------------------------作者:itrycn
using System;
using System.Data;
using System.Data.SQLite;
//数据库操作类
namespace ryCommonDb
{
    /// <summary>
    /// 
    /// </summary>
    public class ClsDb
    {
        /// <summary>
        /// 
        /// </summary>
        public ClsDb()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        ~ClsDb()
        {
            CloseDb();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DbFilePath">数据库路径</param>
        /// <param name="PassWord">数据库密码</param>
        /// <returns></returns>
        public ClsDb(string DbFilePath, string PassWord)
        {
            DbPath = DbFilePath;
            DbPassWord = PassWord;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DbFilePath">数据库路径</param>
        /// <returns></returns>
        public ClsDb(string DbFilePath)
        {
            DbPath = DbFilePath;
        }
        /// <summary>
        /// 
        /// </summary>
        public SQLiteConnection SQLite_cn;
        /// <summary>
        /// 
        /// </summary>
        public string DbPath = "";
        /// <summary>
        /// 
        /// </summary>
        public string DbPassWord = "";
        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <returns></returns>
        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; }
        }
        /// <summary>
        /// 设置路径和密码
        /// </summary>
        /// <returns></returns>
        public int SetPathPwd(string Path, string PassWord)
        {
                DbPath = Path;
                DbPassWord = PassWord;
                return 1;
        }
        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <returns></returns>
        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; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="newPwd"></param>
        public void ChangePwd(string newPwd)
        {
            SQLite_cn.ChangePassword(newPwd);
        }
        /// <summary>
        /// 连接或创建数据库，如果数据库不存在，就创建，否则连接
        /// </summary>
        /// <returns></returns>
        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; }
        }
        /// <summary>
        /// 连接或创建数据库，如果数据库不存在，就创建，否则连接
        /// </summary>
        /// <returns></returns>
        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; }
        }
        /// <summary>
        /// 关闭数据库
        /// </summary>
        /// <returns></returns>
        public void CloseDb()
        {
            try
            {
                if (SQLite_cn!=null && SQLite_cn.State != ConnectionState.Closed)
                {
                    SQLite_cn.Close();
                }
            }
            catch { }
        }
        /// <summary>
        /// 运行SQL命令
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <returns>运行失败，则返回-1，否则返回影响的行数</returns>
        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;
            }
        }
        /// <summary>
        /// 运行SQL命令
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <returns>运行失败，则返回-1，否则返回影响的行数</returns>
        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;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <returns>运行失败，则返回null，否则返回以数组显示的字符串</returns>
        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;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <param name="DefFristValue">数组第一个默认的值</param>
        /// <returns>运行失败，则返回null，否则返回以数组显示的字符串</returns>
        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;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <returns>运行失败，则返回null，否则返回以数组显示的字符串</returns>
        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;
            }
        }
        /// <summary>
        /// 运行SQL命令,并返回结果
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="DefFristValue">数组第一个默认的值</param>
        /// <returns>运行失败，则返回DefFristValue，否则返回以数组显示的字符串</returns>
        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;
            }
        }
        /// <summary>
        /// 清空指定表的所有数据
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>运行失败，则返回-1，否则返回影响的行数</returns>
        [Obsolete("不建议使用，请使用ClearTableData属性", false)]
        public int DeleteTable(string TableName)
        {
            return ClearTableData(TableName);
        }
        /// <summary>
        /// 清空指定表的所有数据
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>运行失败，则返回-1，否则返回影响的行数</returns>
        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;
            }
        }
        /// <summary>
        /// 判断指定值是否存在
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="valueField">指定值所属字段</param>
        /// <param name="value">指定值</param>
        /// <param name="curId">当前id，如果是新增记录，请填写-1</param>
        /// <returns></returns>
        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;
            }
        }
        /// <summary>
        /// 判断SQL语句是否有结果返回
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <param name="commandParameters">SQL命令参数</param>
        /// <returns>运行失败，则返回-1；存在结果，返回1；不存在结果，返回0</returns>
        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;
            }
        }
        /// <summary>
        /// 判断SQL语句是否有结果返回
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <returns>运行失败，则返回-1；存在结果，返回1；不存在结果，返回0</returns>
        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;
            }
        }
        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="SQLText">SQL语句</param>
        /// <returns></returns>
        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();  
        }
        /// <summary>
        /// 根据内置例子创建数据库
        /// </summary>
        /// <returns></returns>
        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();
        }
        /// <summary>
        /// 保存信息，如果Name不存在，系统会自动创建
        /// </summary>
        /// <returns>返回1，表示成功，0表示失败</returns>
        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;
            }
        }
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <returns></returns>
        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;
            }
        }
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <returns></returns>
        public string GetValueByName(string Name, string TableName)
        {
            return GetValueByName(Name, TableName,"");
        }
    }
}
