国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#操作SQLite方法實例詳解

2020-01-24 01:46:57
字體:
來源:轉載
供稿:網友

本文實例講述了C#操作SQLite方法。分享給大家供大家參考。具體分析如下:

地址:

System.Data.Sqlite入手。。。

首先import/using: 

復制代碼 代碼如下:
using System.Data.SQLite;

Connection和Command:

private SQLiteConnection conn; private SQLiteCommand cmd; 

連接db:

conn = new SQLiteConnection("Data Source=c://test.db");  conn.Open(); 

INSERT/UPDATE:

cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO user(email,name) VALUES ('email','name')"; cmd.ExecuteNonQuery();  cmd.CommandText = "UPDATE userSET name = 'Codelicious' WHERE ID = 1"; cmd.ExecuteNonQuery(); 

SELECT:

cmd.CommandText = "SELECT ID, name FROM user"; SQLiteDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) {   while (reader.Read())   {    Console.WriteLine("ID: " + reader.GetInt16(0));    Console.WriteLine("name: " + reader.GetString(1));   } }

模板程序:

using System; using System.Data; using System.Data.Common; using System.Data.SQLite; namespace SQLiteQueryBrowser {    /// <summary>    /// 說明:這是一個針對System.Data.SQLite的數據庫常規操作封裝的通用類。    /// </summary>    public class SQLiteDBHelper    {      private string connectionString = string.Empty;      /// <summary>      /// 構造函數      /// </summary>      /// <param name="dbPath">SQLite數據庫文件路徑</param>      public SQLiteDBHelper(string dbPath)      {        this.connectionString = "Data Source=" + dbPath;      }      /// <summary>      /// 創建SQLite數據庫文件      /// </summary>      /// <param name="dbPath">要創建的SQLite數據庫文件路徑</param>      public static void CreateDB(string dbPath)      {        using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath))        {          connection.Open();          using (SQLiteCommand command = new SQLiteCommand(connection))          {            command.CommandText = "CREATE TABLE Demo(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE)";            command.ExecuteNonQuery();            command.CommandText = "DROP TABLE Demo";            command.ExecuteNonQuery();          }        }      }      /// <summary>      /// 對SQLite數據庫執行增刪改操作,返回受影響的行數。      /// </summary>      /// <param name="sql">要執行的增刪改的SQL語句</param>      /// <param name="parameters">執行增刪改語句所需要的參數,參數必須以它們在SQL語句中的順序為準</param>      /// <returns></returns>      public int ExecuteNonQuery(string sql, SQLiteParameter[] parameters)      {        int affectedRows = 0;        using (SQLiteConnection connection = new SQLiteConnection(connectionString))        {          connection.Open();          using (DbTransaction transaction = connection.BeginTransaction())          {            using (SQLiteCommand command = new SQLiteCommand(connection))            {              command.CommandText = sql;              if (parameters != null)              {                command.Parameters.AddRange(parameters);              }              affectedRows = command.ExecuteNonQuery();            }            transaction.Commit();          }        }        return affectedRows;      }      /// <summary>      /// 執行一個查詢語句,返回一個關聯的SQLiteDataReader實例      /// </summary>      /// <param name="sql">要執行的查詢語句</param>      /// <param name="parameters">執行SQL查詢語句所需要的參數,參數必須以它們在SQL語句中的順序為準</param>      /// <returns></returns>      public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] parameters)      {        SQLiteConnection connection = new SQLiteConnection(connectionString);        SQLiteCommand command = new SQLiteCommand(sql, connection);        if (parameters != null)        {          command.Parameters.AddRange(parameters);        }        connection.Open();        return command.ExecuteReader(CommandBehavior.CloseConnection);      }      /// <summary>      /// 執行一個查詢語句,返回一個包含查詢結果的DataTable      /// </summary>      /// <param name="sql">要執行的查詢語句</param>      /// <param name="parameters">執行SQL查詢語句所需要的參數,參數必須以它們在SQL語句中的順序為準</param>      /// <returns></returns>      public DataTable ExecuteDataTable(string sql, SQLiteParameter[] parameters)      {        using (SQLiteConnection connection = new SQLiteConnection(connectionString))        {          using (SQLiteCommand command = new SQLiteCommand(sql, connection))          {            if (parameters != null)            {              command.Parameters.AddRange(parameters);            }            SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);            DataTable data = new DataTable();            adapter.Fill(data);            return data;          }        }      }      /// <summary>      /// 執行一個查詢語句,返回查詢結果的第一行第一列      /// </summary>      /// <param name="sql">要執行的查詢語句</param>      /// <param name="parameters">執行SQL查詢語句所需要的參數,參數必須以它們在SQL語句中的順序為準</param>      /// <returns></returns>      public Object ExecuteScalar(string sql, SQLiteParameter[] parameters)      {        using (SQLiteConnection connection = new SQLiteConnection(connectionString))        {          using (SQLiteCommand command = new SQLiteCommand(sql, connection))          {            if (parameters != null)            {              command.Parameters.AddRange(parameters);            }            SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);            DataTable data = new DataTable();            adapter.Fill(data);            return data;          }        }      }      /// <summary>      /// 查詢數據庫中的所有數據類型信息      /// </summary>      /// <returns></returns>      public DataTable GetSchema()      {        using (SQLiteConnection connection = new SQLiteConnection(connectionString))        {          connection.Open();          DataTable data=connection.GetSchema("TABLES");          connection.Close();          //foreach (DataColumn column in data.Columns)          //{          //  Console.WriteLine(column.ColumnName);          //}          return data;        }      }    } }

完整的程序例子:

using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using System.Data.SQLite; using SQLiteQueryBrowser; namespace SQLiteDemo {    class Program    {      static void Main(string[] args)      {        //CreateTable();        //InsertData();        ShowData();        Console.ReadLine();      }      public static void CreateTable()      {        string dbPath = "D://Demo.db3";        //如果不存在改數據庫文件,則創建該數據庫文件        if (!System.IO.File.Exists(dbPath))        {          SQLiteDBHelper.CreateDB("D://Demo.db3");        }        SQLiteDBHelper db = new SQLiteDBHelper("D://Demo.db3");        string sql = "CREATE TABLE Test3(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,Name char(3),TypeName varchar(50),addDate datetime,UpdateTime Date,Time time,Comments blob)";        db.ExecuteNonQuery(sql, null);      }      public static void InsertData()      {        string sql = "INSERT INTO Test3(Name,TypeName,addDate,UpdateTime,Time,Comments)values(@Name,@TypeName,@addDate,@UpdateTime,@Time,@Comments)";        SQLiteDBHelper db = new SQLiteDBHelper("D://Demo.db3");        for (char c = "A"; c <= "Z"; c++)        {          for (int i = 0; i < 100; i++)          {            SQLiteParameter[] parameters = new SQLiteParameter[]{              new SQLiteParameter("@Name",c+i.ToString()),            new SQLiteParameter("@TypeName",c.ToString()),            new SQLiteParameter("@addDate",DateTime.Now),            new SQLiteParameter("@UpdateTime",DateTime.Now.Date),            new SQLiteParameter("@Time",DateTime.Now.ToShortTimeString()),            new SQLiteParameter("@Comments","Just a Test"+i)            };            db.ExecuteNonQuery(sql, parameters);          }        }      }      public static void ShowData()      {        //查詢從50條起的20條記錄        string sql = "select * from test3 order by id desc limit 50 offset 20";        SQLiteDBHelper db = new SQLiteDBHelper("D://Demo.db3");        using (SQLiteDataReader reader = db.ExecuteReader(sql, null))        {          while (reader.Read())          {            Console.WriteLine("ID:{0},TypeName{1}", reader.GetInt64(0), reader.GetString(1));          }        }      }    }  }

在實際情況中,采用通用類大批量插入數據會有些慢,這是因為在System.Data.SQLite中的操作如果沒有指定操作,則會被當做一個事物,如果需要一次性寫入大量記錄,則建議顯式創建一個事物,在這個事務中完成所有的操作比較好,這樣的話比每次操作創建一個事物的效率要提升很多。

最終利用VS2008提供的功能,可以看到里面的數據如下:

需要說明的是在System.Data.SQLite中數據類型的規定不適很嚴格,從創建Test3表的SQL語句來看,表中addDate、UpdateTime、Time分別是DateTime、Date、Time類型字段,但實際上我們插入的時候沒有按照這個規定,最終顯示的結果也是盡量遵循數據庫字段的定義。

總結

System.Data.SQLite確實是一個非常小巧精悍的數據庫,作為對SQLite的封裝(SQLite可以在Android等類型的手機上利用Java訪問),它依然是體較小,同比性能高、內存消耗小、無需安裝僅需一個dll就可以運行的優點(如果在Mobile手機上則需要兩個文件),唯一的一個缺點是沒有比較的GUI(圖形用戶界面),不過正因為如此它才得以體積小。

在實際開發中沒有圖形用戶界面可能有些不便,我們可以使用VS來查看和操作數據,我自己也做了一個小東東,便于管理和維護數據,界面如下:

如果你要開發數據量在10萬條以下的應用,我建議你嘗試使用一下System.Data.SQLite,它或許是一個不錯的選擇。

public static void CreateTable(){ string dbPath = "D://Demo.db3"; //如果不存在改數據庫文件,則創建該數據庫文件  if (!System.IO.File.Exists(dbPath)) {  SQLiteDBHelper.CreateDB("D://Demo.db3"); } SQLiteDBHelper db = new SQLiteDBHelper("D://Demo.db3"); string sql = "CREATE TABLE Test3(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,Name char(3),TypeName varchar(50),addDate datetime,UpdateTime Date,Time time,Comments blob)"; db.ExecuteNonQuery(sql, null);}public static void InsertData(){ string sql = "INSERT INTO Test3(Name,TypeName,addDate,UpdateTime,Time,Comments)values(@Name,@TypeName,@addDate,@UpdateTime,@Time,@Comments)"; SQLiteDBHelper db = new SQLiteDBHelper("D://Demo.db3"); for (char c = "A"; c <= "Z"; c++) {  for (int i = 0; i < 100; i++)  {   SQLiteParameter[] parameters = new SQLiteParameter[]{            new SQLiteParameter("@Name",c+i.ToString()),          new SQLiteParameter("@TypeName",c.ToString()),          new SQLiteParameter("@addDate",DateTime.Now),          new SQLiteParameter("@UpdateTime",DateTime.Now.Date),          new SQLiteParameter("@Time",DateTime.Now.ToShortTimeString()),          new SQLiteParameter("@Comments","Just a Test"+i)          };   db.ExecuteNonQuery(sql, parameters);  } }}public static void ShowData(){ //查詢從50條起的20條記錄  string sql = "select * from test3 order by id desc limit 50 offset 20"; SQLiteDBHelper db = new SQLiteDBHelper("D://Demo.db3"); using (SQLiteDataReader reader = db.ExecuteReader(sql, null)) {  while (reader.Read())  {   Console.WriteLine("ID:{0},TypeName{1}", reader.GetInt64(0), reader.GetString(1));  } }}

希望本文所述對大家的C#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 高淳县| 云龙县| 溧水县| 德化县| 民丰县| 阜康市| 民丰县| 阜阳市| 浦东新区| 新河县| 南汇区| 桑日县| 象州县| 祥云县| 江永县| 房山区| 惠安县| 上犹县| 陈巴尔虎旗| 民和| 大厂| 吉木萨尔县| 苍溪县| 岫岩| 赣榆县| 阳朔县| 濮阳县| 通城县| 广饶县| 饶平县| 锡林浩特市| 玛纳斯县| 湘乡市| 宁晋县| 温州市| 晋江市| 象山县| 东平县| 区。| 淳化县| 福安市|