您的位置:首页 > 数据库

PC软件开发技术之三:C#操作SQLite数据库

2018-11-25 04:48 274 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/foxclever/article/details/84460372

我们在开发应用是经常会需要用到一些数据的存储,存储的方式有多种,使用数据库是一种比较受大家欢迎的方式。但是对于一些小型的应用,如一些移动APP,通常的数据库过于庞大,而轻便的SQLite则能解决这一问题。不但操作方便,而且只需要要一个文件即可,在这里我们来说一说使用C#语言操作SQLite数据库。

1、SQLite简介

SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起MySQL、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比他们都快。

如果想了解更多关于SQLite的问题,可以访问它的官方网站:http://www.sqlite.org/

2、开始前的准备

在开始之前我们需要准备必要的开发环境,这次咱们使用的是Visual Studio 2015开发环境,但是我们开发基于SQLite的应用光有VS2015还不够。我需要到SQLite的官方网站下载并安装SQLite。

在SQLite官网找到下载,有应用于各种环境的SQLite组件及源码,我们选择Precompiled Binaries for .NET,这是应用于.NET开发环境的,点击进入会看到应用于.NET2.0直至4.6以及32位和64位平台的各个版本。我们选择Setups for 32-bit Windows (.NET Framework 4.6)下载安装即可。

3、C#操作SQLite的封装

在完成开发环境的准备之后,我们接下来实现对SQLite操作的必要封装,以进一步降低在具体应用中的使用难度。在这里我们只是封装一些常用而且必要的功能。

    public class SQLiteHelper

    {

        //创建数据库文件

        public static void CreateDBFile(string fileName)

        {

            string path = System.Environment.CurrentDirectory + @"/Data/";

            if (!Directory.Exists(path))

            {

                Directory.CreateDirectory(path);

            }

            string databaseFileName = path + fileName;

            if (!File.Exists(databaseFileName))

            {

                SQLiteConnection.CreateFile(databaseFileName);

            }

        }

 

        //生成连接字符串

 

        private static string CreateConnectionString()

        {

            SQLiteConnectionStringBuilder connectionString = new SQLiteConnectionStringBuilder();

            connectionString.DataSource = @"data/ScriptHelper.db";

 

            string conStr = connectionString.ToString();

            return conStr;

        }

 

        /// <summary>

        /// 对插入到数据库中的空值进行处理

        /// </summary>

        /// <param name="value"></param>

        /// <returns></returns>

        public static object ToDbValue(object value)

        {

            if (value == null)

            {

                return DBNull.Value;

            }

            else

            {

                return value;

            }

        }

 

        /// <summary>

        /// 对从数据库中读取的空值进行处理

        /// </summary>

        /// <param name="value"></param>

        /// <returns></returns>

        public static object FromDbValue(object value)

        {

            if (value == DBNull.Value)

            {

                return null;

            }

            else

            {

                return value;

            }

        }

 

        /// <summary>

        /// 执行非查询的数据库操作

        /// </summary>

        /// <param name="sqlString">要执行的sql语句</param>

        /// <param name="parameters">参数列表</param>

        /// <returns>返回受影响的条数</returns>

        public static int ExecuteNonQuery(string sqlString, params SQLiteParameter[] parameters)

        {

            string connectionString=CreateConnectionString();

            using (SQLiteConnection conn = new SQLiteConnection(connectionString))

            {

                conn.Open();

                using (SQLiteCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = sqlString;

                    foreach (SQLiteParameter parameter in parameters)

                    {

                        cmd.Parameters.Add(parameter);

                    }

                    return cmd.ExecuteNonQuery();

                }

            }

        }

 

        /// <summary>

        /// 执行查询并返回查询结果第一行第一列

        /// </summary>

        /// <param name="sqlString">SQL语句</param>

        /// <param name="sqlparams">参数列表</param>

        /// <returns></returns>

        public static object ExecuteScalar(string sqlString, params SQLiteParameter[] parameters)

        {

            string connectionString = CreateConnectionString();

            using (SQLiteConnection conn = new SQLiteConnection(connectionString))

            {

                conn.Open();

                using (SQLiteCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = sqlString;

                    foreach (SQLiteParameter parameter in parameters)

                    {

                        cmd.Parameters.Add(parameter);

                    }

                    return cmd.ExecuteScalar();

                }

            }

        }

 

        /// <summary>

        /// 查询多条数据

        /// </summary>

        /// <param name="sqlString">SQL语句</param>

        /// <param name="parameters">参数列表</param>

        /// <returns>返回查询的数据表</returns>

        public static DataTable GetDataTable(string sqlString,params SQLiteParameter[] parameters)

        {

            string connectionString = CreateConnectionString();

            using (SQLiteConnection conn = new SQLiteConnection(connectionString))

            {

                conn.Open();

                using (SQLiteCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = sqlString;

                    foreach (SQLiteParameter parameter in parameters)

                    {

                        cmd.Parameters.Add(parameter);

                    }

                    DataSet ds = new DataSet();

                    SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);

                    adapter.Fill(ds);

                    return ds.Tables[0];

                }

            }

        }

    }

 

4、应用实例

上面封装完了之后,我们就是使用上面封装的函数来实际操作SQLite数据库。对数据库的应用实例无非就是对各种对象的增、删、改、查。我没列举一个对源码类型对象的各种操作实例如下:

    public class ScriptTypeDAL

    {

        public ScriptTypeM ToScriptType(DataRow row)

        {

            ScriptTypeM type = new ScriptTypeM();

            type.ScriptTypeId = (Guid)row["ScriptTypeId"];

            type.ScriptType = (string)row["ScriptType"];

            type.IsUsing = (bool)row["IsUsing"];

            return type;

        }

 

        public void Insert(ScriptTypeM Type)

        {

            SQLiteHelper.ExecuteNonQuery(@"insert into TB_ScriptType(ScriptTypeId,ScriptType,IsUsing)

                                           Values(@ScriptTypeId,@ScriptType,1)",

                                           new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId),

                                           new SQLiteParameter("ScriptType", Type.ScriptType));

        }

 

        public void Update(ScriptTypeM Type)

        {

            SQLiteHelper.ExecuteNonQuery(@"update TB_ScriptType set ScriptType=@ScriptType,

                                           IsUsing=@IsUsing where ScriptTypeId=@ScriptTypeId",

                                           new SQLiteParameter("ScriptType", Type.ScriptType),

                                           new SQLiteParameter("IsUsing", Type.IsUsing),

                                           new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId));

        }

 

        public ScriptTypeM GetbyId(Guid id)

        {

            DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where ScriptTypeId=@id",

                                                        new SQLiteParameter("id", id));

            if (table.Rows.Count <= 0)

            {

                return null;

            }

            else if (table.Rows.Count > 1)

            {

                throw new Exception("Id重复!");

            }

            else

            {

                return ToScriptType(table.Rows[0]);

            }

        }

 

        public ScriptTypeM GetbyName(string name)

        {

            DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where ScriptType=@name",

                                                        new SQLiteParameter("name", name));

            if (table.Rows.Count <= 0)

            {

                return null;

            }

            else if (table.Rows.Count > 1)

            {

                throw new Exception("类型名称重复!");

            }

            else

            {

                return ToScriptType(table.Rows[0]);

            }

        }

 

        public ScriptTypeM[] ListAll()

        {

            DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where IsUsing=1");

            ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];

            for (int i = 0; i < table.Rows.Count; i++)

            {

                type[i] = ToScriptType(table.Rows[i]);

            }

            return type;

        }

 

        public ScriptTypeM[] Search(string sql, List<SQLiteParameter> parameterList)

        {

            DataTable table = SQLiteHelper.GetDataTable(sql, parameterList.ToArray());

            ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];

            for (int i = 0; i < table.Rows.Count; i++)

            {

                type[i] = ToScriptType(table.Rows[i]);

            }

            return type;

        }

    }

SQLite数据库小巧而且应用方便,在一些小型应用和嵌入式应用中很有优势,当然如何应用的得心应手就看个人了。

欢迎关注:

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐