c#操作轻型数据库SQLite

来源:互联网 发布:比特彗星for mac 编辑:程序博客网 时间:2024/05/01 22:23

       SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。SQLite第一个Alpha版本诞生于2000年5月。 至今已经有12个年头,SQLite也迎来了一个版本 SQLite 3已经发布。

1、通过Add References引用SQLite ADO .NET安装目录的bin目录下的System.Data.SQLite.DLL。

2、创建数据库文件:
   新建数据库文件的相关代码为:
   System.Data.SQLite.SQLiteConnection.CreateFile(datasource);

3、连接数据库
    System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(connectionString);
    connectionString中包含了数据库的一些配置信息,比如数据库文件,数据库打开的密码等,可以利用System.Data.SQLite.SQLiteConnectionStringBuilder来辅助创建connectionString

4、创建表、读取数据等和Access或MS SQL没多大区别了。

5、下面是我参考网上的资料之后自己琢磨出来的完整的例子

            try
            {
                //创建一个数据库文件 
                string datasource = "D:/Temp/Test.db";
               //SQLiteConnection.CreateFile(datasource);  //创建新的数据库 使用时注意,如果已经存在,则覆盖旧的数据库
                //连接数据库 
                SQLiteConnection conn = new SQLiteConnection();
                SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
                connstr.DataSource = datasource;
                //connstr.Password = "admin";//设置密码,SQLite ADO.NET实现了数据库密码保护 
                conn.ConnectionString = connstr.ToString();
                conn.Open();

                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = conn;      //设置连接         

                //创建表 
                string sql = "CREATE TABLE test(username varchar(20),password varchar(20))";  
                /*                                                 
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                */

                //插入数据    
                /*
                sql = "INSERT INTO test VALUES('卡尔萨斯','mypassword')";
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();

                sql = "INSERT INTO test VALUES('露娜','mypassword')";
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                */

                //取出数据 
                sql = "SELECT * FROM test";
                cmd.CommandText = sql;
                SQLiteDataReader reader = cmd.ExecuteReader(); 

自己的测试例子:

例1、

      /// <summary>        /// 读取数据库信息获取具体当前数据库版本号        /// </summary>        /// <parameter>        /// 数据库的路径        /// </parameter>        /// <returns>        /// 返回当前数据库版本号        /// </returns>        public static int getCurrentDBVersion(string DBpath)        {            int myVersion = 0;            SQLiteConnection connection = null;            try            {                //data source=C:\\DataBaseNew.s3db                connection = new SQLiteConnection(DBpath);                SQLiteCommand command = new SQLiteCommand(connection);                command.CommandText = "select value from configurationtable where key=\'LowerLimit\'";                connection.Open();                //执行查询,并返回查询所返回的结果集中第一行的第一列。 忽略其他列或行。                object myversion = command.ExecuteScalar();                connection.Close();                myVersion = Convert.ToInt32(myversion);                //if (Convert.ToInt32(myversion) == 2)                return myVersion;            }            catch (Exception ex)            {                MessageBox.Show(ex.ToString(), "getCurrentDBVersion",MessageBoxButtons.OK,MessageBoxIcon.Error);            }            return myVersion;        }


例2、

/// <summary>        /// 检测数据库中的关键字VersionTable是否存在        /// </summary>        /// <param name="config">数据库路径,需要查找的关键字</param>        /// <returns>true成功,false失败</returns>        public static bool CheckTable(string DBpath, string VersionTable)        {            SQLiteConnection con = null;            con = new SQLiteConnection(DBpath);            SQLiteCommand command = new SQLiteCommand(con);            command.CommandText = "select VersionNUM from " + VersionTable;            try            {                con.Open();                object obj = command.ExecuteScalar();                int i = Convert.ToInt32(obj);                if (i > 0)                {                    con.Close();                    return true;                }                else                {                    con.Close();                    return false;                }            }            catch (Exception ex)            {                MessageBox.Show("执行ExecuteNonQuery()返回值 {0}" + ex.ToString(), "请核对",                    MessageBoxButtons.OK, MessageBoxIcon.Question);                try                {                    command.CommandText = "create table VersionTablegggg(VersionNUM INTEGER primary key, UpdateTime TIMESTAMP not null)";                    command.ExecuteNonQuery();                    command.CommandText = "insert into VersionTablegggg values(1, '" + DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss") + "')";                    command.ExecuteNonQuery();                    con.Close();                }                catch (Exception exp)                {                    MessageBox.Show("执行ExecuteNonQuery()返回值 {0}" + exp.ToString(), "请核对",                        MessageBoxButtons.OK, MessageBoxIcon.Question);                    return false;                }                return true;            }        }
例3、
 /// <summary>        /// 插入一条版本号数据        /// </summary>        /// <param name=" DBpath" ,name=" oldVer">数据库路径和旧版本号</param>        /// <returns>true成功,false失败</returns>        public static bool VersionAddOne(string DBpath, int oldVer)        {            int newVer = oldVer + 1;            SQLiteConnection DBsql = null;            string updatetime = DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss");            MessageBox.Show("updatetime={0}" + updatetime, "VersionAddOne()函数测试", MessageBoxButtons.OK, MessageBoxIcon.Question);            SQLiteParameter[] parameter = { new SQLiteParameter("@VersionNUM", newVer),                                               new SQLiteParameter("@UpdateTime", updatetime) };            DBsql = new SQLiteConnection(DBpath);            string cmd = "insert into VersionTable values(@VersionNUM, @UpdateTime)";            SQLiteCommand command = new SQLiteCommand(cmd, DBsql);            foreach (SQLiteParameter p in parameter)                command.Parameters.Add(p);            try            {                DBsql.Open();                object VersionAddOneReturn = command.ExecuteNonQuery();                DBsql.Close();            }            catch (Exception ex)            {                MessageBox.Show("updatetime={0}" + ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Question);                return false;            }            return true;        }

参考出处:原文来自互联网