当前位置: 首页 > 编程文章 >

C#操作SQLite数据库方法小结(创建,连接,插入,查询,删除等)

C#操作SQLite数据库方法小结(创建,连接,插入,查询,删除等)

作者:许安时间:2026-04-26 16:38:16浏览:806

本文介绍在C#中通过System.Data.SQLite驱动操作SQLite数据库的完整流程,涵盖新建项目、添加引用、连接字符串配置及基础CRUD实现。同时提供基于CodeProject的SQLiteHelper封装类示例,帮助开发者简化常用数据库操作。

本文目录展开

C#操作SQLite数据库方法小结

本实例详解C#对SQLite数据库的操作方式,供读者参考学习。

SQLite简介

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

作为一款开源免费的轻量级关系型数据库管理系统(RDBMS),SQLite具备独立运行、无需服务器进程、零配置及事务支持特性。其由C语言编写,内存开销低,并兼容绝大多数SQL92标准。

SQLite官方主页地址:http://www.sqlite.org/index.html

C#操作SQLite数据库

在C#环境中操作SQLite所需的驱动DLL为:System.Data.SQLite。

C#中使用SQLite的主要步骤如下:

(1)新建一个项目 (2)添加SQLite操作驱动DLL的引用 (3)调用API进行SQLite数据库操作


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()
    {
      string sql = "insert into highscores (name, score) values ('Me', 3000)";
      SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
      command.ExecuteNonQuery();
      sql = "insert into highscores (name, score) values ('Myself', 6000)";
      command = new SQLiteCommand(sql, m_dbConnection);
      command.ExecuteNonQuery();
      sql = "insert into highscores (name, score) values ('And I', 9001)";
      command = new SQLiteCommand(sql, m_dbConnection);
      command.ExecuteNonQuery();
    }
    //使用sql查询语句,并显示结果
    void printHighscores()
    {
      string sql = "select * from highscores order by score desc";
      SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
      SQLiteDataReader reader = command.ExecuteReader();
      while (reader.Read())
        Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]);
      Console.ReadLine();
    }
  }
}

关于SQLite连接字符串的详细说明可参考:http://www.connectionstrings.com/sqlite/

SQLite图形界面客户端列表见:http://www.sqlite.org/cvstrac/wiki?p=ManagementTools

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

用于操作SQLite数据库的C#辅助类:SQLite Helper

将常用功能封装为SQLite Helper类,以提升开发效率。


using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
using System.Collections;
using System.Data.SQLite;
namespace DBUtility.SQLite
{
  /// 
  /// SQLiteHelper is a utility class similar to "SQLHelper" in MS
  /// Data Access Application Block and follows similar pattern.
  /// 
  public class SQLiteHelper
  {
    /// 
    /// Creates a new  instance. The ctor is marked private since all members are static.
    /// 
    private SQLiteHelper()
    {
    }
    /// 
    /// Creates the command.
    /// 
    /// Connection.
    /// Command text.
    /// Command parameters.
    /// SQLite Command
    public static SQLiteCommand CreateCommand(SQLiteConnection connection, string commandText, params SQLiteParameter[] commandParameters)
    {
      SQLiteCommand cmd = new SQLiteCommand(commandText, connection);
      if (commandParameters.Length > 0)
      {
        foreach (SQLiteParameter parm in commandParameters)
          cmd.Parameters.Add(parm);
      }
      return cmd;
    }
    /// 
    /// Creates the command.
    /// 
    /// Connection string.
    /// Command text.
    /// Command parameters.
    /// SQLite Command
    public static SQLiteCommand CreateCommand(string connectionString, string commandText, params SQLiteParameter[] commandParameters)
    {
      SQLiteConnection cn = new SQLiteConnection(connectionString);
      SQLiteCommand cmd = new SQLiteCommand(commandText, cn);
      if (commandParameters.Length > 0)
      {
        foreach (SQLiteParameter parm in commandParameters)
          cmd.Parameters.Add(parm);
      }
      return cmd;
    }
    /// 
    /// Creates the parameter.
    /// 
    /// Name of the parameter.
    /// Parameter type.
    /// Parameter value.
    /// SQLiteParameter
    public static SQLiteParameter CreateParameter(string parameterName, System.Data.DbType parameterType, 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 string
    /// SQL Statement with embedded "@param" style parameter names
    /// object[] array of parameter values
    /// 
    public static DataSet ExecuteDataSet(string connectionString, string commandText, 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
    /// 
    /// Connection.
    /// Command text.
    /// Param list.
    /// 
    public static DataSet ExecuteDataSet(SQLiteConnection cn, string commandText, object[] paramList)
    {
      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;
    }
    /// 
    /// Executes the dataset from a populated Command object.
    /// 
    /// Fully populated SQLiteCommand
    /// DataSet
    public static 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
    /// 
    /// SQLiteTransaction. Transaction consists of Connection, Transaction, /// and Command, all of which must be created prior to making this method call. 
    /// Command text.
    /// Sqlite Command parameters.
    /// DataSet
    /// user must examine Transaction Object and handle transaction.connection .Close, etc.
    public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, params SQLiteParameter[] commandParameters)
    {
      if (transaction == null) throw new ArgumentNullException("transaction");
      if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed, please provide an open transaction.", "transaction");
      IDbCommand cmd = transaction.Connection.CreateCommand();
      cmd.CommandText = commandText;
      foreach (SQLiteParameter parm in commandParameters)
      {
        cmd.Parameters.Add(parm);
      }
      if (transaction.Connection.State == ConnectionState.Closed)
        transaction.Connection.Open();
      DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
      return ds;
    }
    /// 
    /// Executes the dataset with Transaction and object array of parameter values.
    /// 
    /// SQLiteTransaction. Transaction consists of Connection, Transaction,  /// and Command, all of which must be created prior to making this method call. 
    /// Command text.
    /// object[] array of parameter values.
    /// DataSet
    /// user must examine Transaction Object and handle transaction.connection .Close, etc.
    public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, object[] commandParameters)
    {
      if (transaction == null) throw new ArgumentNullException("transaction");
      if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed,                             please provide an open transaction.", "transaction");
      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.
    /// 
    /// 
    /// e.g.: 
    /// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
    /// 
    /// A valid SQL statement to insert new records into the data source
    /// A valid SQL statement to delete records from the data source
    /// A valid SQL statement used to update records in the data source
    /// The DataSet used to update the data source
    /// The DataTable used to update the data source.
    public static void UpdateDataset(SQLiteCommand insertCommand, SQLiteCommand deleteCommand, SQLiteCommand updateCommand, DataSet dataSet, string tableName)
    {
      if (insertCommand == null) throw new ArgumentNullException("insertCommand");
      if (deleteCommand == null) throw new ArgumentNullException("deleteCommand");
      if (updateCommand == null) throw new ArgumentNullException("updateCommand");
      if (tableName == null || tableName.Length == 0) throw new ArgumentNullException("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 Object
    /// SQL Statement with optional embedded "@param" style parameters
    /// object[] array of parameter values
    /// IDataReader
    public static IDataReader ExecuteReader(SQLiteCommand cmd, string commandText, object[] paramList)
    {
      if (cmd.Connection == null)
        throw new ArgumentException("Command must have live connection attached.", "cmd");
      cmd.CommandText = commandText;
      AttachParameters(cmd,commandText, 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 String
    /// Sql Statement with embedded "@param" style parameters
    /// object[] array of parameter values
    /// 
    public static int ExecuteNonQuery(string connectionString, string commandText, params object[] paramList)
    {
      SQLiteConnection cn = new SQLiteConnection(connectionString);
      SQLiteCommand cmd = cn.CreateCommand();
      cmd.CommandText = commandText;
      AttachParameters(cmd,commandText, paramList);
      if (cn.State == ConnectionState.Closed)
        cn.Open();
      int result = cmd.ExecuteNonQuery();
      cmd.Dispose();
      cn.Close();
      return result;
    }
    public static int ExecuteNonQuery(SQLiteConnection cn, string commandText, params object[] paramList)
    {
      SQLiteCommand cmd = cn.CreateCommand();
      cmd.CommandText = commandText;
      AttachParameters(cmd,commandText, paramList);
      if (cn.State == ConnectionState.Closed)
        cn.Open();
      int result = cmd.ExecuteNonQuery();
      cmd.Dispose();
      cn.Close();
      return result;
    }
    /// 
    /// Executes non-query sql Statment with Transaction
    /// 
    /// SQLiteTransaction. Transaction consists of Connection, Transaction,  /// and Command, all of which must be created prior to making this method call. 
    /// Command text.
    /// Param list.
    /// Integer
    /// user must examine Transaction Object and handle transaction.connection .Close, etc.
    public static int ExecuteNonQuery(SQLiteTransaction transaction, string commandText, params object[] paramList)
    {
      if (transaction == null) throw new ArgumentNullException("transaction");
      if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed,                            please provide an open transaction.", "transaction");
      IDbCommand cmd = transaction.Connection.CreateCommand();
      cmd.CommandText = commandText;
      AttachParameters((SQLiteCommand)cmd,cmd.CommandText, paramList);
      if (transaction.Connection.State == ConnectionState.Closed)
        transaction.Connection.Open();
      int result = cmd.ExecuteNonQuery();
      cmd.Dispose();
      return result;
    }
    /// 
    /// Executes the non query.
    /// 
    /// CMD.
    /// 
    public static int ExecuteNonQuery(IDbCommand cmd)
    {
      if (cmd.Connection.State == ConnectionState.Closed)
        cmd.Connection.Open();
      int result = cmd.ExecuteNonQuery();
      cmd.Connection.Close();
      cmd.Dispose();
      return result;
    }
    /// 
    /// Shortcut to ExecuteScalar with Sql Statement embedded params and object[] param values
    /// 
    /// SQLite Connection String
    /// SQL statment with embedded "@param" style parameters
    /// object[] array of param values
    /// 
    public static object ExecuteScalar(string connectionString, string commandText, params object[] paramList)
    {
      SQLiteConnection cn = new SQLiteConnection(connectionString);
      SQLiteCommand cmd = cn.CreateCommand();
      cmd.CommandText = commandText;
      AttachParameters(cmd,commandText, paramList);
      if (cn.State == ConnectionState.Closed)
        cn.Open();
      object result = cmd.ExecuteScalar();
      cmd.Dispose();
      cn.Close();
      return result;
    }
    /// 
    /// Execute XmlReader with complete Command
    /// 
    /// SQLite Command
    /// XmlReader
    public static 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 = new DataSet();
      // 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 ,  /// and returns fully populated ParameterCollection.
    /// 
    /// Sql Statement with "@param" style embedded parameters
    /// object[] array of parameter values
    /// SQLiteParameterCollection
    /// Status 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, string commandText, params object[] paramList)
    {
      if (paramList == null || paramList.Length == 0) return 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(",", " ,");
      // 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"):
          case ("Char"):
          case ("SByte"):
          case ("UInt16"):
          case ("UInt32"):
          case ("UInt64"):
            throw new SystemException("Invalid data type");
          case ("System.String"):
            parm.DbType = DbType.String;
            parm.ParameterName = paramNames[j];
            parm.Value = (string)paramList[j];
            coll.Add(parm);
            break;
          case ("System.Byte[]"):
            parm.DbType = DbType.Binary;
            parm.ParameterName = paramNames[j];
            parm.Value = (byte[])paramList[j];
            coll.Add(parm);
            break;
          case ("System.Int32"):
            parm.DbType = DbType.Int32;
            parm.ParameterName = paramNames[j];
            parm.Value = (int)paramList[j];
            coll.Add(parm);
            break;
          case ("System.Boolean"):
            parm.DbType = DbType.Boolean;
            parm.ParameterName = paramNames[j];
            parm.Value = (bool)paramList[j];
            coll.Add(parm);
            break;
          case ("System.DateTime"):
            parm.DbType = DbType.DateTime;
            parm.ParameterName = paramNames[j];
            parm.Value = Convert.ToDateTime(paramList[j]);
            coll.Add(parm);
            break;
          case ("System.Double"):
            parm.DbType = DbType.Double;
            parm.ParameterName = paramNames[j];
            parm.Value = Convert.ToDouble(paramList[j]);
            coll.Add(parm);
            break;
          case ("System.Decimal"):
            parm.DbType = DbType.Decimal;
            parm.ParameterName = paramNames[j];
            parm.Value = Convert.ToDecimal(paramList[j]);
            break;
          case ("System.Guid"):
            parm.DbType = DbType.Guid;
            parm.ParameterName = paramNames[j];
            parm.Value = (System.Guid)(paramList[j]);
            break;
          case ("System.Object"):
            parm.DbType = DbType.Object;
            parm.ParameterName = paramNames[j];
            parm.Value = paramList[j];
            coll.Add(parm);
            break;
          default:
            throw new SystemException("Value is of unknown data type");
        } // end switch
        j++;
      }
      return coll;
    }
    /// 
    /// Executes non query typed params from a DataRow
    /// 
    /// Command.
    /// Data row.
    /// Integer result code
    public static int 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 > 0)
      {
        // 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 values
    /// The dataRow used to hold the command's parameter values
    /// Thrown if any of the parameter names are invalid.
    protected internal static void AssignParameterValues(IDataParameterCollection commandParameters, DataRow dataRow)
    {
      if (commandParameters == null || dataRow == null)
      {
        // Do nothing if we get no data
        return;
      }
      DataColumnCollection columns = dataRow.Table.Columns;
      int i = 0;
      // Set the parameters values
      foreach (IDataParameter commandParameter in commandParameters)
      {
        // Check the parameter name
        if (commandParameter.ParameterName == null ||
         commandParameter.ParameterName.Length <= 1)
          throw 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 values
    /// The dataRow used to hold the stored procedure's parameter values
    /// Thrown if any of the parameter names are invalid.
    protected void AssignParameterValues(IDataParameter[] commandParameters, DataRow dataRow)
    {
      if ((commandParameters == null) || (dataRow == null))
      {
        // Do nothing if we get no data
        return;
      }
      DataColumnCollection columns = dataRow.Table.Columns;
      int i = 0;
      // Set the parameters values
      foreach (IDataParameter commandParameter in commandParameters)
      {
        // Check the parameter name
        if (commandParameter.ParameterName == null ||
         commandParameter.ParameterName.Length <= 1)
          throw 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 an array of values to an array of IDataParameters
    /// 
    /// Array of IDataParameters to be assigned values
    /// Array of objects holding the values to be assigned
    /// Thrown if an incorrect number of parameters are passed.
    protected void AssignParameterValues(IDataParameter[] commandParameters, params object[] parameterValues)
    {
      if ((commandParameters == null) || (parameterValues == null))
      {
        // Do nothing if we get no data
        return;
      }
      // We must have the same number of values as we pave parameters to put them in
      if (commandParameters.Length != parameterValues.Length)
      {
        throw new ArgumentException("Parameter count does not match Parameter Value count.");
      }
      // Iterate through the IDataParameters, assigning the values from the corresponding position in the 
      // value array
      for (int i = 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;
            }
          }
          else 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

希望本文所述内容能对大家的C#程序设计有所帮助。

上一篇
Swift 3.0 集成 SQLite 数据库完整步骤与代码示例

本文介绍在 Swift 3.0 项目中集成 SQLite 数据库的具体步骤。首先通过 CocoaPods 导入 sqlite3 库,随后配置 Objective-C 桥接文件以支持混合编程。接着封装一个基于单例模式的 sqliteManager 类,负责数据库路径获取、连接打开及 SQL 执行。最后在 AppDelegate 中调用该管理类完成数据库初始化,实现数据的本地持久化存储。

下一篇
Android SQLite数据库创建与使用详解

本文介绍在Android应用中集成SQLite数据库的方法。SQLite是一款轻量级嵌入式关系型数据库,具有进程内引擎、单文件存储及多语言接口等特性。开发者需继承SQLiteOpenHelper类来管理数据库的创建与版本升级,并通过SQLiteDatabase实例执行建表、增删改查等操作。查询结果由Cursor对象返回,便于遍历数据。此外,文章还涵盖了利用adb命令导出和查看数据库文件的实用技巧。

相关文章

更多
PHP SQLite 核心特性与常见并发及类型问题解析

本文针对 PHP 开发中常用的 SQLite 数据库,深入解析其核心机制与常见误区。重点阐述 INTEGER PRIMARY KEY 实现自增的逻辑差异及 AUTOINCREMENT 的作用,解释 SQLite 非严格类型约束下的“列亲和性”原理,并分析在 NFS 或 Windows FAT 环境下多进程并发读写时的锁机制限制与解决方案。

2026.08.14 967
PHP基于PDO实现的SQLite操作类代码示例

本文介绍了一个基于PHP PDO扩展实现的SQLite数据库操作类,该类封装了常见的增删改查功能以及事务处理机制。使用时需特别注意正确配置数据库文件的保存路径,以确保数据持久化存储。该实现旨在为开发者提供一套简洁、可复用的数据库交互方案,便于在PHP项目中快速集成SQLite支持。

2026.05.07 929
SpringBoot整合SQLite数据库全过程

本文介绍如何在SpringBoot项目中集成轻量级SQLite数据库。SQLite具备进程内、无服务器、零配置及ACID事务等特性,适合小型应用或嵌入式场景。通过引入spring-boot-starter-jdbc和sqlite-jdbc依赖,并在application.properties中指定jdbc:sqlite协议的数据源URL,即可实现连接。文章提供了完整的测试代码示例,演示了使用JdbcTemplate进行建表、插入、查询及删除数据的操作流程。

2025.01.31 883
Swift 3.0 集成 SQLite 数据库完整步骤与代码示例

本文介绍在 Swift 3.0 项目中集成 SQLite 数据库的具体步骤。首先通过 CocoaPods 导入 sqlite3 库,随后配置 Objective-C 桥接文件以支持混合编程。接着封装一个基于单例模式的 sqliteManager 类,负责数据库路径获取、连接打开及 SQL 执行。最后在 AppDelegate 中调用该管理类完成数据库初始化,实现数据的本地持久化存储。

2026.01.30 837
PHP实现的sqlite数据库连接类

本文介绍了一个基于PHP的SQLite数据库连接类,该类封装了数据库连接、查询执行及结果处理等核心功能。通过定义connect、query等方法,实现了与SQLite数据库的稳定交互,支持持续连接与非持续连接模式,并提供获取记录数、影响行数及错误信息等辅助功能,便于在PHP项目中快速集成SQLite数据库操作。

2026.06.10 835
JS+HTML5操作SQLite数据库的方法

本文介绍在JavaScript结合HTML5环境下操作SQLite数据库的具体实现方法。通过封装openDatabase接口,提供初始化、建表及数据增删改查功能,帮助开发者在浏览器端进行本地数据存储与交互。

2026.08.22 760

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。