加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

C#操作SQLite数据库

发布时间:2021-07-06 05:53:36 所属栏目:大数据 来源: https://blog.csdn.net/kasama1
导读:C#操作SQLite数据库 sqlite介绍 sqlite is a software library that implements a?self-contained,?serverless,?zero-configuration,?transactional?sql database engine. sqlite是一个开源、免费的小型RDBMS(关系型数据库),能独立运行、无服务器、零配置、

C#操作SQLite数据库

sqlite介绍

sqlite is a software library that implements a?self-contained,?serverless,?zero-configuration,?transactional?sql database engine.

sqlite是一个开源、免费的小型RDBMS(关系型数据库),能独立运行、无服务器、零配置、支持事物,用C实现,内存占用较小,支持绝大数的sql92标准。

sqlite数据库官方主页:http://www.sqlite.org/index.html

C#操作sqlite Database

C#下sqlite操作驱动dll下载:System.Data.SQLite

C#使用sqlite步骤:

(1)新建一个project

(2)添加sqlite操作驱动dll引用

(3)使用API操作sqlite DataBase

复制代码

using System;
using System.Data.sqlite;

namespace sqliteSamples
{
    class Program
    {
        //数据库连接
        sqliteConnection m_dbConnection;

        static void Main(string[] args)
        {
            Program p = new Program();
        }

        public Program()
        {
            createNewDatabase();
            connectToDatabase();
            createTable();
            fillTable();
            printHighscores();
        }

        创建一个空的数据库
        void createNewDatabase()
        {
            sqliteConnection.CreateFile("MyDatabase.sqlite");
        }

        创建一个连接到指定数据库
        void connectToDatabase()
        {
            m_dbConnection = new sqliteConnection(Data Source=MyDatabase.sqlite;Version=3;");
            m_dbConnection.Open();
        }

        在指定数据库中创建一个table
        void createTable()
        {
            string sql = create table highscores (name varchar(20),score int)";
            sqliteCommand command = new sqliteCommand(sql,m_dbConnection);
            command.ExecuteNonQuery();
        }

        插入一些数据
        void fillTable()
        {
            insert into highscores (name,score) values ('Me',3000)";
            command = 使用SQL查询语句,并显示结果
        void printHighscores()
        {
            select * from highscores order by score desc command.ExecuteReader();
            while (reader.Read())
                Console.WriteLine(Name: " + reader[name"] + tscore: score"]);
            Console.ReadLine();
        }
    }
}

复制代码

关于sqlite的connection string说明:http://www.connectionstrings.com/sqlite/

sqlite GUI客户端列表:http://www.sqlite.org/cvstrac/wiki?p=ManagementTools

sqlite Administrator下载地址:http://download.orbmu2k.de/files/sqliteadmin.zip

操作sqlite Database的C#帮助类sqlite Helper

将一些常用的功能封装一下,封装成sqlite Helper类

复制代码

using System.Data;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
using System.Collections;
namespace DBUtility.sqlite
{
    /// <summary>
    /// sqliteHelper is a utility class similar to "sqlHelper" in MS
     Data Access Application Block and follows similar pattern.
    </summary>
    public class sqliteHelper
    {
        <summary>
         Creates a new <see cref="sqliteHelper"/> instance. The ctor is marked private since all members are static.
        </summary>
        private sqliteHelper()
        {
        }
         Creates the command.
        </summary>
        <param name="connection">Connection.</param>
        <param name="commandText">Command text.<param name="commandParameters">Command parameters.<returns>sqlite Command</returns>
        static sqliteCommand CreateCommand(sqliteConnection connection,string commandText,255); line-height:1.5!important">params sqliteParameter[] commandParameters)
        {
            sqliteCommand cmd = new sqliteCommand(commandText,connection);
            if (commandParameters.Length > 0)
            {
                foreach (sqliteParameter parm in commandParameters)
                    cmd.Parameters.Add(parm);
            }
            return cmd;
        }

        <param name="connectionString">Connection string.static sqliteCommand CreateCommand(string connectionString,255); line-height:1.5!important">params sqliteParameter[] commandParameters)
        {
            sqliteConnection cn = new sqliteConnection(connectionString);

            sqliteCommand cmd = return cmd;
        }
         Creates the parameter.
        <param name="parameterName">Name of the parameter.<param name="parameterType">Parameter type.<param name="parameterValue">Parameter value.sqliteParameterstatic sqliteParameter CreateParameter(string parameterName,System.Data.DbType parameterType,255); line-height:1.5!important">object parameterValue)
        {
            sqliteParameter parameter = new sqliteParameter();
            parameter.DbType = parameterType;
            parameter.ParameterName = parameterName;
            parameter.Value = parameterValue;
            return parameter;
        }

         Shortcut method to execute dataset from sql Statement and object[] arrray of parameter values
        sqlite Connection stringsql Statement with embedded "@param" style parameter names<param name="paramList">object[] array of parameter values<returns></returns>
        static DataSet ExecuteDataSet(object[] paramList)
        {
            sqliteConnection cn = new sqliteConnection(connectionString);
            sqliteCommand cmd = cn.CreateCommand();


            cmd.CommandText = commandText;
            if (paramList != null)
            {
                AttachParameters(cmd,commandText,paramList);
            }
            DataSet ds = new DataSet();
            if (cn.State == ConnectionState.Closed)
                cn.Open();
            sqliteDataAdapter da = new sqliteDataAdapter(cmd);
            da.Fill(ds);
            da.Dispose();
            cmd.Dispose();
            cn.Close();
            return ds;
        }
         Shortcut method to execute dataset from sql Statement and object[] arrray of  parameter values
        <param name="cn">Param list.static DataSet ExecuteDataSet(sqliteConnection cn,255); line-height:1.5!important">object[] paramList)
        {

            sqliteCommand cmd = cn.CreateCommand();


            cmd.CommandText = commandText;
             Executes the dataset from a populated Command object.
        <param name="cmd">Fully populated sqliteCommandDataSetstatic DataSet ExecuteDataset(sqliteCommand cmd)
        {
            if (cmd.Connection.State == ConnectionState.Closed)
                cmd.Connection.Open();
            DataSet ds = new DataSet();
            sqliteDataAdapter da = new sqliteDataAdapter(cmd);
            da.Fill(ds);
            da.Dispose();
            cmd.Connection.Close();
            cmd.Dispose();
            return ds;
        }

         Executes the dataset in a sqlite Transaction
        <param name="transaction">sqliteTransaction. Transaction consists of Connection,Transaction, and Command,all of which must be created prior to making this method call. sqlite Command parameters.</returns>
        <remarks>user must examine Transaction Object and handle transaction.connection .Close,etc.</remarks>
        static DataSet ExecuteDataset(sqliteTransaction transaction,255); line-height:1.5!important">params sqliteParameter[] commandParameters)
        {

            if (transaction == null) throw new ArgumentNullException(transaction");
            if (transaction != null && transaction.Connection == new ArgumentException(The transaction was rolled back or committed,please provide an open transaction.",");
            IDbCommand cmd = transaction.Connection.CreateCommand();
            cmd.CommandText = commandText;
            in commandParameters)
            {
                cmd.Parameters.Add(parm);
            }
            if (transaction.Connection.State == ConnectionState.Closed)
                transaction.Connection.Open();
            DataSet ds = ExecuteDataset((sqliteCommand)cmd);
             Executes the dataset with Transaction and object array of parameter values.
        object[] array of parameter values.object[] commandParameters)
        {

            ");
            IDbCommand cmd = transaction.Connection.CreateCommand();
            cmd.CommandText = commandText;
            AttachParameters((sqliteCommand)cmd,cmd.CommandText,commandParameters);
            if (transaction.Connection.State == ConnectionState.Closed)
                transaction.Connection.Open();

            DataSet ds = ExecuteDataset((sqliteCommand)cmd);
            return ds;
        }

        #region UpdateDataset
         Executes the respective command for each inserted,updated,or deleted row in the DataSet.
        <remarks>
         e.g.:  
          UpdateDataset(conn,insertCommand,deleteCommand,updateCommand,dataSet,"Order");
        </remarks>
        <param name="insertCommand">A valid sql statement  to insert new records into the data source<param name="deleteCommand">A valid sql statement to delete records from the data source<param name="updateCommand">A valid sql statement used to update records in the data source<param name="dataSet">The DataSet used to update the data source<param name="tableName">The DataTable used to update the data source.</param>
        void UpdateDataset(sqliteCommand insertCommand,sqliteCommand deleteCommand,sqliteCommand updateCommand,DataSet dataSet,255); line-height:1.5!important">string tableName)
        {
            if (insertCommand == insertCommandif (deleteCommand == deleteCommandif (updateCommand == updateCommandif (tableName == null || tableName.Length == 0) tableName");

             Create a sqliteDataAdapter,and dispose of it after we are done
            using (sqliteDataAdapter dataAdapter = new sqliteDataAdapter())
            {
                 Set the data adapter commands
                dataAdapter.UpdateCommand = updateCommand;
                dataAdapter.InsertCommand = insertCommand;
                dataAdapter.DeleteCommand = deleteCommand;

                 Update the dataset changes in the data source
                dataAdapter.Update(dataSet,tableName);

                 Commit all the changes made to the DataSet
                dataSet.AcceptChanges();
            }
        }
        #endregion




         ShortCut method to return IDataReader
         NOTE: You should explicitly close the Command.connection you passed in as
         well as call Dispose on the Command  after reader is closed.
         We do this because IDataReader has no underlying Connection Property.
        sqliteCommand Objectsql Statement with optional embedded "@param" style parametersIDataReaderstatic IDataReader ExecuteReader(sqliteCommand cmd,255); line-height:1.5!important">object[] paramList)
        {
            if (cmd.Connection == null)
                Command must have live connection attached.cmd");
            cmd.CommandText = commandText;
            AttachParameters(cmd,paramList);
            if (cmd.Connection.State == ConnectionState.Closed)
                cmd.Connection.Open();
            IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return rdr;
        }

         Shortcut to ExecuteNonQuery with sqlStatement and object[] param values
        sqlite Connection Stringsql Statement with embedded "@param" style parametersint ExecuteNonQuery(params new sqliteConnection(connectionString);
            sqliteCommand cmd = cn.CreateCommand();
            cmd.CommandText = commandText;
            AttachParameters(cmd,255); line-height:1.5!important">if (cn.State == ConnectionState.Closed)
                cn.Open();
            int result = cmd.ExecuteNonQuery();
            cmd.Dispose();
            cn.Close();

            return result;
        }



        int ExecuteNonQuery(sqliteConnection cn,255); line-height:1.5!important">params  object[] paramList)
        {

            sqliteCommand cmd = cn.CreateCommand();
            cmd.CommandText = commandText;
            AttachParameters(cmd,255); line-height:1.5!important">return result;
        }

         Executes  non-query sql Statment with Transaction
        Integerint ExecuteNonQuery(sqliteTransaction transaction,255); line-height:1.5!important">if (transaction.Connection.State == ConnectionState.Closed)
                transaction.Connection.Open();
            int result = cmd.ExecuteNonQuery();
            cmd.Dispose();
            return result;
        }


         Executes the non query.
        CMD.int ExecuteNonQuery(IDbCommand cmd)
        {
            if (cmd.Connection.State == ConnectionState.Closed)
                cmd.Connection.Open();
            int result = cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            cmd.Dispose();
             Shortcut to ExecuteScalar with sql Statement embedded params and object[] param values
        sql statment with embedded "@param" style parametersobject[] array of param valuesobject ExecuteScalar(object result = cmd.ExecuteScalar();
            cmd.Dispose();
            cn.Close();

             Execute XmlReader with complete Command
        <param name="command">XmlReaderstatic XmlReader ExecuteXmlReader(IDbCommand command)
        {  open the connection if necessary,but make sure we 
             know to close it when we?re done.
            if (command.Connection.State != ConnectionState.Open)
            {
                command.Connection.Open();
            }

             get a data adapter  
            sqliteDataAdapter da = new sqliteDataAdapter((sqliteCommand)command);
            DataSet ds =  fill the data set,and return the schema information
            da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            da.Fill(ds);
             convert our dataset to XML
            StringReader stream = new StringReader(ds.GetXml());
            command.Connection.Close();
             convert our stream of text to an XmlReader
            return new XmlTextReader(stream);
        }



         Parses parameter names from sql Statement,assigns values from object array,0); line-height:1.5!important"> and returns fully populated ParameterCollection.
        sql Statement with "@param" style embedded parameterssqliteParameterCollectionStatus experimental. Regex appears to be handling most issues. Note that parameter object array must be in same order as parameter names appear in sql statement.private static sqliteParameterCollection AttachParameters(sqliteCommand cmd,255); line-height:1.5!important">if (paramList == null || paramList.Length == null;

            sqliteParameterCollection coll = cmd.Parameters;
            string parmString = commandText.Substring(commandText.IndexOf(@"));
             pre-process the string so always at least 1 space after a comma.
            parmString = parmString.Replace(,0); line-height:1.5!important"> get the named parameters into a match collection
            string pattern = @"(@)S*(.*?)b";
            Regex ex = new Regex(pattern,RegexOptions.IgnoreCase);
            MatchCollection mc = ex.Matches(parmString);
            string[] paramNames = new string[mc.Count];
            int i = 0;
            foreach (Match m in mc)
            {
                paramNames[i] = m.Value;
                i++;
            }

             now let's type the parameters
            int j = 0;
            Type t = null;
            foreach (object o in paramList)
            {
                t = o.GetType();

                sqliteParameter parm = new sqliteParameter();
                switch (t.ToString())
                {

                    case (DBNull"):
                    CharSByteUInt16UInt32UInt64"):
                        new SystemException(Invalid data type");


                    System.String"):
                        parm.DbType = DbType.String;
                        parm.ParameterName = paramNames[j];
                        parm.Value = (string)paramList[j];
                        coll.Add(parm);
                        break;

                    System.Byte[]"):
                        parm.DbType = DbType.Binary;
                        parm.ParameterName = paramNames[j];
                        parm.Value = (byte[])paramList[j];
                        coll.Add(parm);
                        System.Int32"):
                        parm.DbType = DbType.Int32;
                        parm.ParameterName = paramNames[j];
                        parm.Value = (int)paramList[j];
                        coll.Add(parm);
                        System.Boolean"):
                        parm.DbType = DbType.Boolean;
                        parm.ParameterName = paramNames[j];
                        parm.Value = (bool)paramList[j];
                        coll.Add(parm);
                        System.DateTime"):
                        parm.DbType = DbType.DateTime;
                        parm.ParameterName = paramNames[j];
                        parm.Value = Convert.ToDateTime(paramList[j]);
                        coll.Add(parm);
                        System.Double"):
                        parm.DbType = DbType.Double;
                        parm.ParameterName = paramNames[j];
                        parm.Value = Convert.ToDouble(paramList[j]);
                        coll.Add(parm);
                        System.Decimal"):
                        parm.DbType = DbType.Decimal;
                        parm.ParameterName = paramNames[j];
                        parm.Value = Convert.ToDecimal(paramList[j]);
                        System.Guid"):
                        parm.DbType = DbType.Guid;
                        parm.ParameterName = paramNames[j];
                        parm.Value = (System.Guid)(paramList[j]);
                        System.Object"):

                        parm.DbType = DbType.Object;
                        parm.ParameterName = paramNames[j];
                        parm.Value = paramList[j];
                        coll.Add(parm);
                        default:
                        Value is of unknown data type");

                }  end switch

                j++;
            }
            return coll;
        }

         Executes non query typed params from a DataRow
        Command.<param name="dataRow">Data row.Integer result codeint ExecuteNonQueryTypedParams(IDbCommand command,DataRow dataRow)
        {
            int retVal = 0;

             If the row has values,the store procedure parameters must be initialized
            if (dataRow != null && dataRow.ItemArray.Length >  Set the parameters values
                AssignParameterValues(command.Parameters,dataRow);

                retVal = ExecuteNonQuery(command);
            }
            else
            {
                retVal = ExecuteNonQuery(command);
            }

            return retVal;
        }

         This method assigns dataRow column values to an IDataParameterCollection
        The IDataParameterCollection to be assigned valuesThe dataRow used to hold the command's parameter values<exception cref="System.InvalidOperationException">Thrown if any of the parameter names are invalid.</exception>
        protected internal void AssignParameterValues(IDataParameterCollection commandParameters,255); line-height:1.5!important">if (commandParameters == null || dataRow == null)
            {
                 Do nothing if we get no data
                return;
            }

            DataColumnCollection columns = dataRow.Table.Columns;

             Set the parameters values
            foreach (IDataParameter commandParameter in commandParameters)
            {
                 Check the parameter name
                if (commandParameter.ParameterName == null ||
                 commandParameter.ParameterName.Length <= 1)
                    new InvalidOperationException(string.Format(
                           Please provide a valid parameter name on the parameter #{0},the ParameterName property has the following value: '{1}'.",i,commandParameter.ParameterName));

                if (columns.Contains(commandParameter.ParameterName))
                    commandParameter.Value = dataRow[commandParameter.ParameterName];
                else if (columns.Contains(commandParameter.ParameterName.Substring(1)))
                    commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];

                i++;
            }
        }

         This method assigns dataRow column values to an array of IDataParameters
        Array of IDataParameters to be assigned valuesThe dataRow used to hold the stored procedure's parameter valuesvoid AssignParameterValues(IDataParameter[] commandParameters,255); line-height:1.5!important">if ((commandParameters == null) || (dataRow == null))
            {
                string.Format(
                      This method assigns an array of values to an array of IDataParameters
        <param name="parameterValues">Array of objects holding the values to be assigned<exception cref="System.ArgumentException">Thrown if an incorrect number of parameters are passed.void AssignParameterValues(IDataParameter[] commandParameters,255); line-height:1.5!important">object[] parameterValues)
        {
            null) || (parameterValues == return;
            }

             We must have the same number of values as we pave parameters to put them in
            if (commandParameters.Length != parameterValues.Length)
            {
                Parameter count does not match Parameter Value count.");
            }

             Iterate through the IDataParameters,assigning the values from the corresponding position in the 
             value array
            for (0,j = commandParameters.Length,k = 0; i < j; i++)
            {
                if (commandParameters[i].Direction != ParameterDirection.ReturnValue)
                {
                     If the current array value derives from IDataParameter,then assign its Value property
                    if (parameterValues[k] is IDataParameter)
                    {
                        IDataParameter paramInstance;
                        paramInstance = (IDataParameter)parameterValues[k];
                        if (paramInstance.Direction == ParameterDirection.ReturnValue)
                        {
                            paramInstance = (IDataParameter)parameterValues[++k];
                        }
                        if (paramInstance.Value == null)
                        {
                            commandParameters[i].Value = DBNull.Value;
                        }
                        else
                        {
                            commandParameters[i].Value = paramInstance.Value;
                        }
                    }
                    if (parameterValues[k] == null)
                    {
                        commandParameters[i].Value = DBNull.Value;
                    }
                    else
                    {
                        commandParameters[i].Value = parameterValues[k];
                    }
                    k++;
                }
            }
        }
    }
}

复制代码

Codeproject上的一个封装:http://www.codeproject.com/Articles/746191/sqlite-Helper-Csharp

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读