当前位置:数据库 > SQLite >>

C#——SQLite速成

为什么我需要SQLite

* 轻巧灵活,基于单个数据库文件,方便创建、移动,能方便的进行数据的分类存储(按业务、按功能、按日期、按客户等),非常适合与灵活的系统搭配使用。

* 部署容易,.NET环境只需一个dll文件(Access可能需要安装MDAC)。

* 开源。

 

SQLite开发环境与开发资料的准备

.Net SQLite数据库驱动:System.Data.SQLite.dll以及文档

SQLite GUI数据库工具:SQLite Expert PersonalEdition(个人版免费,够用了)

.Net SQLite数据库驱动源码:sqlite-netFx-source-1.0.76.0

 

C#动态创建SQLite数据库

调用SQLiteConnection. CreateFile静态方法创建

SQLiteConnection.CreateFile(path)

 

path测试路径:Data目录存在,Data2目录不存在

                var path1 = "dummy1.db";//成功

                var path2 = "Data/dummy2.db";//成功

                var path3 = "Data\\dummy3.db";//成功

                var path4 = "c:\\Data\\dummy4.db";//成功

                var path5 = "Data2//dummy5.db";//错误,Data2目录不存在

           var path6 = "C:\\Data2\\dummy6.db";//错误,Data2目录不存在

 

SQLiteConnection. CreateFile内部的实现源码:使用了File.Create创建0字节文件

    /// <summary>

    /// Creates a database file.  This just creates a zero-byte file whichSQLite

    /// will turn into a database when the file is openedproperly.

    /// </summary>

    /// <paramname="databaseFileName">Thefile to create</param>

    static public void CreateFile(string databaseFileName)

    {

      FileStream fs = File.Create(databaseFileName);

      fs.Close();

    }

 

C#连接SQLite与数据库安全

常用的连接字符串生成

                /// <summary>

                /// 生成SQLite连接字符串

                /// </summary>

                public static class SQLiteConnectionString

                {

                                public static string GetConnectionString(stringpath)

                                {

                                                return GetConnectionString(path,null);

                                }

                                public static string GetConnectionString(stringpath, string password)

                                {

                                                if (string.IsNullOrEmpty(password))

                                                                return "Data Source=" + path;

                                                return "Data Source=" + path + ";Password=" + password;

                                }

                }

修改数据库密码

                /// <summary>

                /// 修改密码

                /// </summary>

                /// <paramname="path"></param>

                /// <param name="newPassword"></param>

                /// <param name="oldPassword">没有密码时为空</param>

                public static boolChangePassword(stringpath, string newPassword,string oldPassword = null)

                {

                                try

          &nbs

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,