码迷,mamicode.com
首页 > 数据库 > 详细

C#中使用SQLite

时间:2020-06-17 01:42:08      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:man   while   select   增删改查   nec   down   类型   values   console   

最近要做一个单机小程序,但涉及到一些数据的存取和增删改查,研究了一番,觉得还是轻量级数据库sqlite最合适,于是先做了个样例,方便进一步开发。

 

sqlite可以在如下网址下载

https://www.sqlite.org/download.html

但可直接下载System.Data.SQLite用在c#中,在如下网址下载

http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

我选择了其中的Precompiled Binaries for 64-bit Windows (.NET Framework 4.0)

sqlite-netFx40-binary-bundle-x64-2010-1.0.113.0.zip

不过貌似需要tunnel cross great wall。也可下载我文末的样例程序包,里面已经包含了必要的库及帮助文件。

 

新建工程,因为下载的是64位SQLite库,在配制管理器中修改工程为x64架构。

技术图片

然后引用中添加System.Data.SQLite.dll即可使用。

 

程序本身比较简单,核心是下面的SQLite帮助类,用于封装一些函数,便于调用。直接上代码,每个函数都有注释,也比较简单。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLiteDemo
{
    public enum SQLiteType
    {
        INTEGER,
        REAL,
        TEXT,
        BLOB
    }

    class SQLiteHelper
    {
        string m_connString;

        public SQLiteHelper(string databasepath)
        {
            m_connString = "data source = " + databasepath;
            if (!File.Exists(databasepath))
            {
                SQLiteConnection.CreateFile(databasepath);
            }
        }

        /// <summary>
        /// 执行不带参数的SQL语句
        /// </summary>
        /// <param name="cmdString">SQL语句</param>
        /// <returns>受影响的行数</returns>
        public int Execute(string cmdString)
        {
            using (SQLiteConnection conn = new SQLiteConnection(m_connString))
            {
                using (SQLiteCommand command = new SQLiteCommand(cmdString, conn))
                {
                    try
                    {
                        conn.Open();
                        int row = command.ExecuteNonQuery();
                        return row;
                    }
                    catch (SQLiteException e)
                    {
                        conn.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 批量执行SQL语句
        /// </summary>
        /// <param name="cmdStrings">要批量执行的所有SQL语句</param>
        public void BatchExecute(string[] cmdStrings)
        {
            using (SQLiteConnection conn = new SQLiteConnection(m_connString))
            {
                conn.Open();
                SQLiteTransaction trans = conn.BeginTransaction();
                SQLiteCommand command = new SQLiteCommand(conn);
                command.Transaction = trans;
                try
                {
                    for (int i = 0; i < cmdStrings.Length; i++)
                    {
                        command.CommandText = cmdStrings[i];
                        command.ExecuteNonQuery();
                    }
                    trans.Commit();
                }
                catch (SQLiteException e)
                {
                    trans.Rollback();
                    throw new Exception(e.Message);
                }
            }
        }

        /// <summary>
        /// 创建数据表
        /// </summary>
        /// <param name="tableName">数据表名</param>
        /// <param name="colNames">所有列名称</param>
        /// <param name="colTypes">每一列的类型</param>
        /// <param name="infos">每一列的其他描述,比如是否可为NULL,是否为主键</param>
        /// <returns>返回数据表Reader</returns>
        public SQLiteDataReader CreateTable(string tableName, string[] colNames, SQLiteType[] colTypes, string[] infos = null)
        {
            string cmd = "CREATE TABLE IF NOT EXISTS " + tableName + "( ";
            for (int i = 0; i < colNames.Length; i++)
            {
                cmd += colNames[i] + " " + colTypes[i].ToString();
                if (infos != null)
                {
                    cmd += " " + infos[i];
                }
                if (i != colNames.Length - 1)
                {
                    cmd += ", ";
                }
            }
            cmd += " )";

            return Select(cmd);
        }

        /// <summary>
        /// 删除数据表
        /// </summary>
        /// <param name="tableName">要删除的数据表</param>
        /// <returns>该表的行数</returns>
        public int DropTable(string tableName)
        {
            string cmd = "DROP TABLE " + tableName;

            return Execute(cmd);
        }

        /// <summary>
        /// 在数据表中插入数据,但不适用于插入二进制数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="types">每一列的类型</param>
        /// <param name="values">每一列的值</param>
        /// <param name="columns">可选参数,每一列的列名</param>
        /// <returns>插入的行数</returns>
        public int InsertData(string tableName, SQLiteType[] types, string[] values, string[] columns = null)
        {
            string cmd = "INSERT INTO " + tableName;
            if (columns != null)
            {
                cmd += " ( ";
                for (int i = 0; i < columns.Length; i++)
                {
                    cmd += columns[i];
                    if (i != columns.Length - 1)
                    {
                        cmd += ", ";
                    }
                }
                cmd += " ) ";
            }
            cmd += " VALUES ( ";
            for (int i = 0; i < values.Length; i++)
            {
                switch (types[i])
                {
                    case SQLiteType.INTEGER:
                    case SQLiteType.REAL:
                        cmd += values[i];
                        break;
                    case SQLiteType.BLOB:
                        throw new Exception("Please use InsertBinary to do the job!");
                    default:
                        cmd += "‘" + values[i] + "‘";
                        break;
                }
                if (i != values.Length - 1)
                {
                    cmd += ", ";
                }
            }
            cmd += " )";

            return Execute(cmd);
        }

        /// <summary>
        /// 执行带参数的SQL语句
        /// </summary>
        /// <param name="cmdString">带参数的SQL语句</param>
        /// <param name="parameters">对应的参数</param>
        /// <returns>受影响的行数</returns>
        private int Execute(string cmdString, SQLiteParameter[] parameters)
        {
            using (SQLiteConnection conn = new SQLiteConnection(m_connString))
            {
                using (SQLiteCommand command = new SQLiteCommand(cmdString, conn))
                {
                    try
                    {
                        conn.Open();
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            command.Parameters.Add(parameters[i]);
                        }

                        int row = command.ExecuteNonQuery();
                        return row;
                    }
                    catch (SQLiteException e)
                    {
                        conn.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 在数据表中插入数据,可用于二进制数据插入
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="columns">列名</param>
        /// <param name="types">每一列的类型</param>
        /// <param name="values">每一列的值</param>
        /// <returns></returns>
        public int InsertBinary(string tableName, string[] columns, SQLiteType[] types, object[] values)
        {
            string cmd = "INSERT INTO " + tableName;
            cmd += " ( ";
            for (int i = 0; i < columns.Length; i++)
            {
                cmd += ", " + columns[i];
            }
            cmd += " ) VALUES ( ";
            for (int i = 0; i < values.Length; i++)
            {
                cmd += "@" + columns[i];
                if (i != values.Length - 1)
                {
                    cmd += ", ";
                }

            }
            cmd += " ) ";

            List<SQLiteParameter> parameters = new List<SQLiteParameter>();
            for (int i = 0; i < types.Length; i++)
            {
                SQLiteParameter sp = new SQLiteParameter();
                sp.ParameterName = "@" + columns[i];
                sp.Value = values[i];
                switch (types[i])
                {
                    case SQLiteType.INTEGER:
                        sp.DbType = DbType.Int64;
                        break;
                    case SQLiteType.REAL:
                        sp.DbType = DbType.Double;
                        break;
                    case SQLiteType.BLOB:
                        sp.DbType = DbType.Binary;
                        break;
                    default:
                        sp.DbType = DbType.String;
                        break;
                }
                parameters.Add(sp);
            }
            return Execute(cmd, parameters.ToArray());
        }

        /// <summary>
        /// 执行不带参数的select语句
        /// </summary>
        /// <param name="cmdString">select语句</param>
        /// <returns>返回的数据列表Reader</returns>
        public SQLiteDataReader Select(string cmdString)
        {
            SQLiteConnection conn = new SQLiteConnection(m_connString);
            SQLiteCommand command = new SQLiteCommand(cmdString, conn);
            try
            {
                conn.Open();
                SQLiteDataReader reader = command.ExecuteReader();
                return reader;
            }
            catch (SQLiteException e)
            {
                conn.Close();
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 从数据库中获得需要的数据并放入DataSet
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="conditions">选择条件,为null则获取所有表中数据</param>
        /// <param name="columns">可选参数,列名</param>
        /// <returns></returns>
        public DataSet Select(string tableName, string conditions, string[] columns = null)
        {
            using (SQLiteConnection conn = new SQLiteConnection(m_connString))
            {
                DataSet ds = new DataSet();
                string cmd = "SELECT ";
                if (columns != null)
                {
                    for (int i = 0; i < columns.Length; i++)
                    {
                        cmd += columns[i];
                        if (i != columns.Length - 1)
                        {
                            cmd += ", ";
                        }
                    }
                }
                else
                {
                    cmd += " * ";
                }
                cmd += " FROM " + tableName;
                if (!string.IsNullOrEmpty(conditions))
                {
                    cmd += " WHERE " + conditions;
                }

                using (SQLiteCommand command = new SQLiteCommand(cmd, conn))
                {
                    try
                    {
                        conn.Open();
                        SQLiteDataAdapter da = new SQLiteDataAdapter(command);
                        da.Fill(ds);
                        da.Dispose();

                        return ds;
                    }
                    catch (SQLiteException e)
                    {
                        conn.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 修改数据,但不适用于修改包含二进制数据的列
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="columns">列名</param>
        /// <param name="values">每一列对应的值,注意如果数据类型是Text,需要将其用单引号‘‘括起来</param>
        /// <param name="conditions">可选参数,修改数据的过滤条件</param>
        /// <returns>受影响的行数</returns>
        public int UpdateData(string tableName, string[] columns, string[] values, string conditions = null)
        {
            string cmd = "UPDATE " + tableName + " SET ";
            for (int i = 0; i < columns.Length; i++)
            {
                cmd += columns[i] + " = " + values[i];
                if (i != columns.Length - 1)
                {
                    cmd += ", ";
                }
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                cmd += " WHERE " + conditions;
            }

            return Execute(cmd);
        }

        /// <summary>
        /// 修改数据,可用于修改二进制数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="columns">列名</param>
        /// <param name="values">每一列对应的值</param>
        /// <param name="types">每一列的类型</param>
        /// <param name="conditions">可选参数,修改数据的过滤条件</param>
        /// <returns>受影响的行数</returns>
        public int UpdateBinary(string tableName, string[] columns, string[] values, SQLiteType[] types, string conditions = null)
        {
            string cmd = "UPDATE " + tableName + " SET ";
            for (int i = 0; i < columns.Length; i++)
            {
                cmd += columns[i] + " = @" + columns[i];
                if (i != columns.Length - 1)
                {
                    cmd += ", ";
                }
            }
            if (!string.IsNullOrEmpty(conditions))
            {
                cmd += " WHERE " + conditions;
            }

            List<SQLiteParameter> parameters = new List<SQLiteParameter>();
            for (int i = 0; i < types.Length; i++)
            {
                SQLiteParameter sp = new SQLiteParameter();
                sp.ParameterName = "@" + columns[i];
                sp.Value = values[i];
                switch (types[i])
                {
                    case SQLiteType.INTEGER:
                        sp.DbType = DbType.Int64;
                        break;
                    case SQLiteType.REAL:
                        sp.DbType = DbType.Double;
                        break;
                    case SQLiteType.BLOB:
                        sp.DbType = DbType.Binary;
                        break;
                    default:
                        sp.DbType = DbType.String;
                        break;
                }
                parameters.Add(sp);
            }

            return Execute(cmd, parameters.ToArray());
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="conditions">删除数据时的过滤条件</param>
        /// <returns>被删除的行数</returns>
        public int DeleteData(string tableName, string conditions = null)
        {
            string cmd = "DELETE FROM " + tableName;
            if (!string.IsNullOrEmpty(conditions))
            {
                cmd += " WHERE " + conditions;
            }

            return Execute(cmd);
        }
    }
}

 

可通过下面的样例程序调用,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLiteDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string database = "test.db";
            string tablename = "TABLE1";
            string[] columns = new string[] { "ID", "NAME", "SALARY"};
            SQLiteType[] types = new SQLiteType[] { SQLiteType.INTEGER, SQLiteType.TEXT, SQLiteType.REAL };
            string[] infos = new string[] { "PRIMARY KEY", "NOT NULL", "" };

            SQLiteHelper helper = new SQLiteHelper(database);
            helper.CreateTable(tablename, columns, types, infos);

            Random r = new Random();
            for (int i = 0; i < 5; i++)
            {
                string[] values = new string[] { i.ToString(), Guid.NewGuid().ToString(), (r.NextDouble() * 10000).ToString() };
                helper.InsertData(tablename, types, values);
            }

            System.Data.DataSet ds = helper.Select(tablename, null, null);
            System.Data.DataTable dt = ds.Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    Console.Write(columns[j] + " : " + dt.Rows[i][j].ToString());
                    if (j != dt.Columns.Count - 1)
                    {
                        Console.Write(", ");
                    }
                    else
                    {
                        Console.Write("\n");
                    }
                }
            }
            Console.WriteLine();

            string[] newValues = new string[] { "10", "‘James‘", "12345.67" };
            string condition1 = "ID = 3";
            helper.UpdateData(tablename, columns, newValues, condition1);
            string condition2 = "ID = 2 OR ID = 0";
            helper.DeleteData(tablename, condition2);
            newValues = new string[] { "123", "Clark", "7654.32" };
            string condition3 = "ID = 1";
            helper.UpdateBinary(tablename, columns, newValues, types, condition3);

            System.Data.SQLite.SQLiteDataReader reader = helper.Select("SELECT * FROM " + tablename);
            while(reader.Read())
            {
                for (int i = 0; i < columns.Length; i++ )
                {
                    Console.Write(columns[i] + " : " + reader[columns[i]]);
                    if (i != columns.Length-1)
                    {
                        Console.Write(", ");
                    }
                    else
                    {
                        Console.Write("\n");
                    }
                }
                
            }

            helper.DropTable(tablename);
            Console.Read();
        }
    }
}

运行结果如下。

技术图片

 

整个VS工程可在下面的网址下载

https://download.csdn.net/download/u014559935/12528241

推荐:站长

C#中使用SQLite

标签:man   while   select   增删改查   nec   down   类型   values   console   

原文地址:https://www.cnblogs.com/1994july/p/13149953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!