美文网首页
C# SQLite 数据库使用说明

C# SQLite 数据库使用说明

作者: 任前程 | 来源:发表于2018-11-04 09:32 被阅读163次

    一、NuGet引入SQLite库

    在VS菜单:工具→NuGet包管理器→管理解决方案的NuGet程序包 打开NuGet解决方案窗口。

    搜索 sqlite,选择官方的库安装到指定的项目中。:

    image.png

    提示:System.Data.SQLite 分为 x86 和 x64 版本,这里推荐使用NuGet自动安装。使用 Any CPU 编译的时候,会自动拷贝32位和64位 Interop DLL文件到子目录中。程序运行的时候会根据电脑的运行环境自动选择合适的dll。

    image.png

    二、DBHelper类库

    using System.Collections.Generic;
    using System.Data;
    using System.Data.SQLite;
    using System.Configuration;
    using System.Data.SqlClient;
    //using MySql.Data.MySqlClient;
    
    namespace ConsoleApp5
    {
        public class DBHelper
        {
            private readonly static string connStr = ConfigurationManager.ConnectionStrings["Data Source=mesclient.sqlite;Version=3"].ConnectionString;
    
            //获取 appsetting 设置的值
            //private readonly static string appStr = ConfigurationManager.AppSettings["TestKey"];
    
            //获取 connection 对象
            public static IDbConnection CreateConnection()
            {
                IDbConnection conn = new SQLiteConnection(connStr);//MySqlConnection //SqlConnection
                conn.Open();
                return conn;
            }
    
            //执行非查询语句
            public static int ExecuteNonQuery(IDbConnection conn, string sql, Dictionary<string, object> parameters)
            {
                using (IDbCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    foreach (KeyValuePair<string, object> keyValuePair in parameters)
                    {
                        IDbDataParameter parameter = cmd.CreateParameter();
                        parameter.ParameterName = keyValuePair.Key;
                        parameter.Value = keyValuePair.Value;
                        cmd.Parameters.Add(parameter);
                    }
                    return cmd.ExecuteNonQuery();
                }
            }
    
            //执行非查询语句-独立连接
            public static int ExecuteNonQuery(string sql, Dictionary<string, object> parameters)
            {
                using (IDbConnection conn = CreateConnection())
                {
                    return ExecuteNonQuery(conn, sql, parameters);
                }
            }
    
            //查询首行首列
            public static object ExecuteScalar(IDbConnection conn, string sql, Dictionary<string, object> parameters)
            {
                using (IDbCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    foreach (KeyValuePair<string, object> keyValuePair in parameters)
                    {
                        IDbDataParameter parameter = cmd.CreateParameter();
                        parameter.ParameterName = keyValuePair.Key;
                        parameter.Value = keyValuePair.Value;
                        cmd.Parameters.Add(parameter);
                    }
                    return cmd.ExecuteScalar();
                }
            }
    
            //查询首行首列-独立连接
            public static object ExecuteScalar(string sql, Dictionary<string, object> parameters)
            {
                using (IDbConnection conn = CreateConnection())
                {
                    return ExecuteScalar(conn, sql, parameters);
                }
            }
    
            //查询表
            public static DataTable ExecuteQuery(IDbConnection conn, string sql, Dictionary<string, object> parameters)
            {
                DataTable dt = new DataTable();
                using (IDbCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    foreach (KeyValuePair<string, object> keyValuePair in parameters)
                    {
                        IDbDataParameter parameter = cmd.CreateParameter();
                        parameter.ParameterName = keyValuePair.Key;
                        parameter.Value = keyValuePair.Value;
                        cmd.Parameters.Add(parameter);
                    }
                    using (IDataReader reader = cmd.ExecuteReader())
                    {
                        dt.Load(reader);
                    }
                }
    
                return dt;
            }
    
            //查询表--独立连接
            public static DataTable ExecuteQuery(string sql, Dictionary<string, object> parameters)
            {
                using (IDbConnection conn = CreateConnection())
                {
                    return ExecuteQuery(conn, sql, parameters);
                }
            }
        }
    }
    
    

    三、基本使用

    1. 判断数据文件是否存在

    /// <summary>
    /// 检查数据库是否存在不存在创建
    /// </summary>
    /// <returns></returns>
    public static bool CheckDataBase()
    {
        try
        {
            //判断数据文件是否存在
            bool dbExist = File.Exists("mesclient.sqlite");
            if (!dbExist)
            {
                SQLiteConnection.CreateFile("mesclient.sqlite");
            }
    
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    
    }
    
    

    2. 判断表是否存在

    /// <summary>
    /// 检查数据表是否存在,不存在创建
    /// </summary>
    /// <returns></returns>
    public static bool CheckDataTable(string connStr)
    {
        try
        {
            using (SQLiteConnection conn = new SQLiteConnection(connStr))
            using (SQLiteCommand cmd = conn.CreateCommand())
            {
                conn.Open();
                cmd.CommandText = "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'serverinfo'";
                object ob = cmd.ExecuteScalar();
                long tableCount = Convert.ToInt64(ob);
                if (tableCount == 0)
                {
                    //创建表
                    cmd.CommandText = @"
                BEGIN;
                    create table serverinfo 
                    (Id INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT,
                    Url text,DelayTime integer,UsageCounter INTEGER,
                     Status integer,CreateTime DATETIME);
                    CREATE UNIQUE INDEX idx_serverInfo ON serverinfo (Name);
                COMMIT;
                ";
                    //此语句返回结果为0
                    int rowCount = cmd.ExecuteNonQuery();
                    return true;
                }
                else if (tableCount > 1)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    
    

    3. 查询

    string sql = "SELECT * FROM serverinfo WHERE Name =@ServerName AND Url = @Url and date(CreateTime)=date(@Date);";
    Dictionary<string, object> parameters = new Dictionary<string, object>();
    parameters.Add("ServerName",endpointElement.Name);
    parameters.Add("Url", endpointElement.Address);
    parameters.Add("Date", DateTime.Now.ToString("yyyy-MM-dd"));
    DataTable dt=SqliteHelper.ExecuteQuery(connStr, sql, parameters);
    if (dt.Rows.Count>0)
    {
        UsageCounter = dt.Rows[0].Field<long>("UsageCounter");
        GetTime = dt.Rows[0].Field<DateTime>("CreateTime");
    }
    
    

    4. 新增/修改

    //存在更新,不存在插入
    string updateSql = "REPLACE INTO serverinfo(Name,Url,DelayTime,UsageCounter, Status,CreateTime) VALUES(@Name,@Url,@DelayTime,@UsageCounter,@Status, @CreateTime)";
    Dictionary<string, object> ups = new Dictionary<string, object>();
    ups.Add("Name", name);
    ups.Add("Url", url);
    ups.Add("DelayTime", delayTime);
    ups.Add("UsageCounter", usageCounter);
    ups.Add("Status", status);
    ups.Add("CreateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
    int count= SqliteHelper.ExecuteNonQuery(connStr, updateSql, ups);
    if (count>0)
    {
        return true;
    }
    else
    {
        return false;
    }
    
    

    5. 删除

    //删除记录
    string updateSql =
        "DELETE FROM serverinfo where content=@Content and flag=@Flag;";
    Dictionary<string, object> updateParameters = new Dictionary<string, object>();
    updateParameters.Add("Content", Content);
    updateParameters.Add("Flag", Flag);
    int count = SqliteHelper.ExecuteNonQuery(connStr, updateSql, updateParameters);
    if (count > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
    
    

    四、参考文章

    1. Create SQLite Database and table

    2. Writing to a SQLite Database in C#

    3. SQLite with VS2012 and .NET 4.5 — ANY CPU Build

    4. how to check if a table exists in C#

    5. SQLite auto increment issue

    6. Inserting a date to SQLite

    7. SQLite REPLACE Statement

    8. sqlite select with condition on date

    9. Using SQLite how do I index columns in a CREATE TABLE statement?


    本文为原创文章,转载请注明出处!欢迎关注任前程博客 https://renqiancheng.com/,第一时间看后续精彩文章。

    相关文章

      网友评论

          本文标题:C# SQLite 数据库使用说明

          本文链接:https://www.haomeiwen.com/subject/pykrxqtx.html