您好,登錄后才能下訂單哦!
這篇文章主要介紹了C#如何操作SQLite實現數據的增刪改查,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
SQLite是一個輕量級、跨平臺的關系型數據庫,在小型項目中,方便,易用,同時支持多種開發語言,下面是我用C#語言對SQLite 的一個封裝。
Winfrom界面如下:
代碼還需要改進部分:
下面的代碼我不覺得是完美的,讀者可以自己去實現這些功能:
1.如果不想用多線程可以去掉UsingLock.cs ,在SQLiteHelper.cs中刪除對應的引用即可。
2.創建數據庫文件,可以從代碼中分離成單獨的方法。比如創建有密碼的數據庫文件。
3.在執行SQL語句時,有些語句執行成功,也不會有影響行數。比如,創建表,刪除表,此時執行SQL語句返回的影響行數就為0。
4.只要SQL語句不報錯就是執行成功的,在方法的返回值可以改為多個,比如用
Tuple<bool, string, int> 第一個參數 bool 代表執行結果,第二個參數 string 代表錯誤信息,第三個參數 int 代表影響的行數。
同樣,也可以這樣:
Tuple<bool, string, DataSet> 第一個參數 bool 代表執行結果,第二個參數 string 代表錯誤信息,第三個參數 DataSet 代表返回的表單數據。
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SQLite; using System.IO; using System.Text; namespace MySQLiteHelper { public class SQLiteHelper { #region 字段 /// <summary> /// 事務的基類 /// </summary> private DbTransaction DBtrans; /// <summary> /// 使用靜態變量字典解決多線程實例本類,實現一個數據庫對應一個clslock /// </summary> private static readonly Dictionary<string, ClsLock> RWL = new Dictionary<string, ClsLock>(); /// <summary> /// 數據庫地址 /// </summary> private readonly string mdataFile; /// <summary> /// 數據庫密碼 /// </summary> private readonly string mPassWord; private readonly string LockName = null; /// <summary> /// 數據庫連接定義 /// </summary> private SQLiteConnection mConn; #endregion #region 構造函數 /// <summary> /// 根據數據庫地址初始化 /// </summary> /// <param name="dataFile">數據庫地址</param> public SQLiteHelper(string dataFile) { this.mdataFile = dataFile ?? throw new ArgumentNullException("dataFile=null"); //this.mdataFile = AppDomain.CurrentDomain.BaseDirectory + dataFile; this.mdataFile = dataFile; if (!RWL.ContainsKey(dataFile)) { LockName = dataFile; RWL.Add(dataFile, new ClsLock()); } } /// <summary> /// 使用密碼打開數據庫 /// </summary> /// <param name="dataFile">數據庫地址</param> /// <param name="PassWord">數據庫密碼</param> public SQLiteHelper(string dataFile, string PassWord) { this.mdataFile = dataFile ?? throw new ArgumentNullException("dataFile is null"); this.mPassWord = PassWord ?? throw new ArgumentNullException("PassWord is null"); //this.mdataFile = AppDomain.CurrentDomain.BaseDirectory + dataFile; this.mdataFile = dataFile; if (!RWL.ContainsKey(dataFile)) { LockName = dataFile; RWL.Add(dataFile, new ClsLock()); } } #endregion #region 打開/關閉 數據庫 /// <summary> /// 打開 SQLiteManager 使用的數據庫連接 /// </summary> public void Open() { if (string.IsNullOrWhiteSpace(mPassWord)) { mConn = OpenConnection(this.mdataFile); } else { mConn = OpenConnection(this.mdataFile, mPassWord); } Console.WriteLine("打開數據庫成功"); } /// <summary> /// 關閉連接 /// </summary> public void Close() { if (this.mConn != null) { try { this.mConn.Close(); if (RWL.ContainsKey(LockName)) { RWL.Remove(LockName); } } catch { Console.WriteLine("關閉失敗"); } } Console.WriteLine("關閉數據庫成功"); } #endregion #region 事務 /// <summary> /// 開始事務 /// </summary> public void BeginTrain() { EnsureConnection(); DBtrans = mConn.BeginTransaction(); } /// <summary> /// 提交事務 /// </summary> public void DBCommit() { try { DBtrans.Commit(); } catch (Exception) { DBtrans.Rollback(); } } #endregion #region 工具 /// <summary> /// 打開一個SQLite數據庫文件,如果文件不存在,則創建(無密碼) /// </summary> /// <param name="dataFile"></param> /// <returns>SQLiteConnection 類</returns> private SQLiteConnection OpenConnection(string dataFile) { if (dataFile == null) { throw new ArgumentNullException("dataFiledataFile=null"); } if (!File.Exists(dataFile)) { SQLiteConnection.CreateFile(dataFile); } SQLiteConnection conn = new SQLiteConnection(); SQLiteConnectionStringBuilder conStr = new SQLiteConnectionStringBuilder { DataSource = dataFile }; conn.ConnectionString = conStr.ToString(); conn.Open(); return conn; } /// <summary> /// 打開一個SQLite數據庫文件,如果文件不存在,則創建(有密碼) /// </summary> /// <param name="dataFile"></param> /// <param name="Password"></param> /// <returns>SQLiteConnection 類</returns> private SQLiteConnection OpenConnection(string dataFile, string Password) { if (dataFile == null) { throw new ArgumentNullException("dataFile=null"); } if (!File.Exists(Convert.ToString(dataFile))) { SQLiteConnection.CreateFile(dataFile); } try { SQLiteConnection conn = new SQLiteConnection(); SQLiteConnectionStringBuilder conStr = new SQLiteConnectionStringBuilder { DataSource = dataFile, Password = Password }; conn.ConnectionString = conStr.ToString(); conn.Open(); return conn; } catch (Exception) { return null; } } /// <summary> /// 讀取 或 設置 SQLiteManager 使用的數據庫連接 /// </summary> public SQLiteConnection Connection { get { return mConn; } private set { mConn = value ?? throw new ArgumentNullException(); } } /// <summary> /// 確保數據庫是連接狀態 /// </summary> /// <exception cref="Exception"></exception> protected void EnsureConnection() { if (this.mConn == null) { throw new Exception("SQLiteManager.Connection=null"); } if (mConn.State != ConnectionState.Open) { mConn.Open(); } } /// <summary> /// 獲取數據庫文件的路徑 /// </summary> /// <returns></returns> public string GetDataFile() { return this.mdataFile; } /// <summary> /// 判斷表 table 是否存在 /// </summary> /// <param name="table"></param> /// <returns>存在返回true,否則返回false</returns> public bool TableExists(string table) { if (table == null) { throw new ArgumentNullException("table=null"); } EnsureConnection(); SQLiteDataReader reader = ExecuteReader("SELECT count(*) as c FROM sqlite_master WHERE type='table' AND name=@tableName ", new SQLiteParameter[] { new SQLiteParameter("tableName", table) }); if (reader == null) { return false; } reader.Read(); int c = reader.GetInt32(0); reader.Close(); reader.Dispose(); //return false; return c == 1; } /// <summary> /// VACUUM 命令(通過復制主數據庫中的內容到一個臨時數據庫文件,然后清空主數據庫,并從副本中重新載入原始的數據庫文件) /// </summary> /// <returns></returns> public bool Vacuum() { try { using (SQLiteCommand Command = new SQLiteCommand("VACUUM", Connection)) { Command.ExecuteNonQuery(); } return true; } catch (System.Data.SQLite.SQLiteException) { return false; } } #endregion #region 執行SQL /// <summary> /// 執行SQL, 并返回 SQLiteDataReader 對象結果 /// </summary> /// <param name="sql"></param> /// <param name="paramArr">null 表示無參數</param> /// <returns></returns> public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] paramArr) { if (sql == null) { throw new ArgumentNullException("sql=null"); } EnsureConnection(); using (RWL[LockName].Read()) { using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection)) { if (paramArr != null) { cmd.Parameters.AddRange(paramArr); } try { SQLiteDataReader reader = cmd.ExecuteReader(); cmd.Parameters.Clear(); return reader; } catch (Exception) { return null; } } } } /// <summary> /// 執行查詢,并返回dataset對象 /// </summary> /// <param name="sql">SQL查詢語句</param> /// <param name="paramArr">參數數組</param> /// <returns></returns> public DataSet ExecuteDataSet(string sql, SQLiteParameter[] paramArr) { if (sql == null) { throw new ArgumentNullException("sql=null"); } this.EnsureConnection(); using (RWL[LockName].Read()) { using (SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection)) { if (paramArr != null) { cmd.Parameters.AddRange(paramArr); } try { SQLiteDataAdapter da = new SQLiteDataAdapter(); DataSet ds = new DataSet(); da.SelectCommand = cmd; da.Fill(ds); cmd.Parameters.Clear(); da.Dispose(); return ds; } catch (Exception) { return null; } } } } /// <summary> /// 執行SQL查詢,并返回dataset對象。 /// </summary> /// <param name="strTable">映射源表的名稱</param> /// <param name="sql">SQL語句</param> /// <param name="paramArr">SQL參數數組</param> /// <returns></returns> public DataSet ExecuteDataSet(string strTable, string sql, SQLiteParameter[] paramArr) { if (sql == null) { throw new ArgumentNullException("sql=null"); } this.EnsureConnection(); using (RWL[LockName].Read()) { using (SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection)) { if (paramArr != null) { cmd.Parameters.AddRange(paramArr); } try { SQLiteDataAdapter da = new SQLiteDataAdapter(); DataSet ds = new DataSet(); da.SelectCommand = cmd; da.Fill(ds, strTable); cmd.Parameters.Clear(); da.Dispose(); return ds; } catch (Exception) { return null; } } } } /// <summary> /// 執行SQL,返回受影響的行數,可用于執行表創建語句,paramArr == null 表示無參數 /// </summary> /// <param name="sql"></param> /// <returns></returns> public int ExecuteNonQuery(string sql, SQLiteParameter[] paramArr) { if (sql == null) { throw new ArgumentNullException("sql=null"); } this.EnsureConnection(); using (RWL[LockName].Read()) { try { using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection)) { if (paramArr != null) { foreach (SQLiteParameter p in paramArr) { cmd.Parameters.Add(p); } } int c = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return c; } } catch (SQLiteException) { return 0; } } } /// <summary> /// 執行SQL,返回結果集第一行,如果結果集為空,那么返回空 List(List.Count=0), /// rowWrapper = null 時,使用 WrapRowToDictionary /// </summary> /// <param name="sql"></param> /// <param name="paramArr"></param> /// <returns></returns> public object ExecuteScalar(string sql, SQLiteParameter[] paramArr) { if (sql == null) { throw new ArgumentNullException("sql=null"); } this.EnsureConnection(); using (RWL[LockName].Read()) { using (SQLiteCommand cmd = new SQLiteCommand(sql, Connection)) { if (paramArr != null) { cmd.Parameters.AddRange(paramArr); } try { object reader = cmd.ExecuteScalar(); cmd.Parameters.Clear(); cmd.Dispose(); return reader; } catch (Exception) { return null; } } } } /// <summary> /// 查詢一行記錄,無結果時返回 null,conditionCol = null 時將忽略條件,直接執行 select * from table /// </summary> /// <param name="table">表名</param> /// <param name="conditionCol"></param> /// <param name="conditionVal"></param> /// <returns></returns> public object QueryOne(string table, string conditionCol, object conditionVal) { if (table == null) { throw new ArgumentNullException("table=null"); } this.EnsureConnection(); string sql = "select * from " + table; if (conditionCol != null) { sql += " where " + conditionCol + "=@" + conditionCol; } object result = ExecuteScalar(sql, new SQLiteParameter[] { new SQLiteParameter(conditionCol, conditionVal) }); return result; } #endregion #region 增 刪 改 /// <summary> /// 執行 insert into 語句 /// </summary> /// <param name="table"></param> /// <param name="entity"></param> /// <returns></returns> public int InsertData(string table, Dictionary<string, object> entity) { if (table == null) { throw new ArgumentNullException("table=null"); } this.EnsureConnection(); string sql = BuildInsert(table, entity); return this.ExecuteNonQuery(sql, BuildParamArray(entity)); } /// <summary> /// 執行 update 語句,注意:如果 where = null,那么 whereParams 也為 null, /// </summary> /// <param name="table">表名</param> /// <param name="entity">要修改的列名和列名的值</param> /// <param name="where">查找符合條件的列</param> /// <param name="whereParams">where條件中參數的值</param> /// <returns></returns> public int Update(string table, Dictionary<string, object> entity, string where, SQLiteParameter[] whereParams) { if (table == null) { throw new ArgumentNullException("table=null"); } this.EnsureConnection(); string sql = BuildUpdate(table, entity); SQLiteParameter[] parameter = BuildParamArray(entity); if (where != null) { sql += " where " + where; if (whereParams != null) { SQLiteParameter[] newArr = new SQLiteParameter[(parameter.Length + whereParams.Length)]; Array.Copy(parameter, newArr, parameter.Length); Array.Copy(whereParams, 0, newArr, parameter.Length, whereParams.Length); parameter = newArr; } } return this.ExecuteNonQuery(sql, parameter); } /// <summary> /// 執行 delete from table 語句,where不必包含'where'關鍵字,where = null 時將忽略 whereParams /// </summary> /// <param name="table"></param> /// <param name="where"></param> /// <param name="whereParams"></param> /// <returns></returns> public int Delete(string table, string where, SQLiteParameter[] whereParams) { if (table == null) { throw new ArgumentNullException("table=null"); } this.EnsureConnection(); string sql = "delete from " + table + " "; if (where != null) { sql += "where " + where; } return ExecuteNonQuery(sql, whereParams); } /// <summary> /// 將 Dictionary 類型數據 轉換為 SQLiteParameter[] 類型 /// </summary> /// <param name="entity"></param> /// <returns></returns> private SQLiteParameter[] BuildParamArray(Dictionary<string, object> entity) { List<SQLiteParameter> list = new List<SQLiteParameter>(); foreach (string key in entity.Keys) { list.Add(new SQLiteParameter(key, entity[key])); } if (list.Count == 0) { return null; } return list.ToArray(); } /// <summary> /// 將 Dictionary 類型數據 轉換為 插入數據 的 SQL語句 /// </summary> /// <param name="table">表名</param> /// <param name="entity">字典</param> /// <returns></returns> private string BuildInsert(string table, Dictionary<string, object> entity) { StringBuilder buf = new StringBuilder(); buf.Append("insert into ").Append(table); buf.Append(" ("); foreach (string key in entity.Keys) { buf.Append(key).Append(","); } buf.Remove(buf.Length - 1, 1); // 移除最后一個, buf.Append(") "); buf.Append("values("); foreach (string key in entity.Keys) { buf.Append("@").Append(key).Append(","); // 創建一個參數 } buf.Remove(buf.Length - 1, 1); buf.Append(") "); return buf.ToString(); } /// <summary> /// 將 Dictionary 類型數據 轉換為 修改數據 的 SQL語句 /// </summary> /// <param name="table">表名</param> /// <param name="entity">字典</param> /// <returns></returns> private string BuildUpdate(string table, Dictionary<string, object> entity) { StringBuilder buf = new StringBuilder(); buf.Append("update ").Append(table).Append(" set "); foreach (string key in entity.Keys) { buf.Append(key).Append("=").Append("@").Append(key).Append(","); } buf.Remove(buf.Length - 1, 1); buf.Append(" "); return buf.ToString(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace MySQLiteHelper { /// <summary> /// 使用using代替lock操作的對象,可指定寫入和讀取鎖定模式 /// </summary> public sealed class ClsLock { #region 內部類 /// <summary> /// 利用IDisposable的using語法糖方便的釋放鎖定操作內部類 /// </summary> private struct Lock : IDisposable { /// <summary> /// 讀寫鎖對象 /// </summary> private readonly ReaderWriterLockSlim _Lock; /// <summary> /// 是否為寫入模式 /// </summary> private bool _IsWrite; /// <summary> /// 利用IDisposable的using語法糖方便的釋放鎖定操作構造函數 /// </summary> /// <param name="rwl">讀寫鎖</param> /// <param name="isWrite">寫入模式為true,讀取模式為false</param> public Lock(ReaderWriterLockSlim rwl, bool isWrite) { _Lock = rwl; _IsWrite = isWrite; } /// <summary> /// 釋放對象時退出指定鎖定模式 /// </summary> public void Dispose() { if (_IsWrite) { if (_Lock.IsWriteLockHeld) { _Lock.ExitWriteLock(); } } else { if (_Lock.IsReadLockHeld) { _Lock.ExitReadLock(); } } } } /// <summary> /// 空的可釋放對象,免去了調用時需要判斷是否為null的問題內部類 /// </summary> private class Disposable : IDisposable { /// <summary> /// 空的可釋放對象 /// </summary> public static readonly Disposable Empty = new Disposable(); /// <summary> /// 空的釋放方法 /// </summary> public void Dispose() { } } #endregion /// <summary> /// 讀寫鎖 /// </summary> private readonly ReaderWriterLockSlim _LockSlim = new ReaderWriterLockSlim(); /// <summary> /// 使用using代替lock操作的對象,可指定寫入和讀取鎖定模式構造函數 /// </summary> public ClsLock() { Enabled = true; } /// <summary> /// 是否啟用,當該值為false時,Read()和Write()方法將返回 Disposable.Empty /// </summary> public bool Enabled { get; set; } /// <summary> /// 進入讀取鎖定模式,該模式下允許多個讀操作同時進行, /// 退出讀鎖請將返回對象釋放,建議使用using語塊, /// Enabled為false時,返回Disposable.Empty, /// 在讀取或寫入鎖定模式下重復執行,返回Disposable.Empty; /// </summary> public IDisposable Read() { if (Enabled == false || _LockSlim.IsReadLockHeld || _LockSlim.IsWriteLockHeld) { return Disposable.Empty; } else { _LockSlim.EnterReadLock(); return new Lock(_LockSlim, false); } } /// <summary> /// 進入寫入鎖定模式,該模式下只允許同時執行一個讀操作, /// 退出讀鎖請將返回對象釋放,建議使用using語塊, /// Enabled為false時,返回Disposable.Empty, /// 在寫入鎖定模式下重復執行,返回Disposable.Empty /// </summary> /// <exception cref="NotImplementedException">讀取模式下不能進入寫入鎖定狀態</exception> public IDisposable Write() { if (Enabled == false || _LockSlim.IsWriteLockHeld) { return Disposable.Empty; } else if (_LockSlim.IsReadLockHeld) { throw new NotImplementedException("讀取模式下不能進入寫入鎖定狀態"); } else { _LockSlim.EnterWriteLock(); return new Lock(_LockSlim, true); } } } }
using MySQLiteHelper; using System; using System.Collections.Generic; using System.Data; using System.Data.SQLite; using System.Windows.Forms; namespace SQLiteDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private SQLiteHelper SQLiteHelpers = null; private const string DBAddress = "D:\\SQLiteData\\test_record.db3"; private void Form1_Load(object sender, EventArgs e) { SQLiteHelpers = new SQLiteHelper(DBAddress,"123456"); } /// <summary> /// 打開數據庫 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_OpenDB_Click(object sender, EventArgs e) { SQLiteHelpers.Open(); Label_DBOpenState.Text = "打開"; } /// <summary> /// 關閉數據庫 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_CloseDB_Click(object sender, EventArgs e) { SQLiteHelpers.Close(); Label_DBOpenState.Text = "關閉"; } /// <summary> /// 查詢 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Query_Click(object sender, EventArgs e) { SQLiteParameter[] parameter = new SQLiteParameter[] { new SQLiteParameter("address", "濟南") }; string sql = "SELECT * FROM student WHERE address = @address"; DataSet dataSet = SQLiteHelpers.ExecuteDataSet(sql, parameter); if (dataSet != null) { dataGridView1.DataSource = dataSet.Tables[0]; } } /// <summary> /// 插入數據 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Add_Click(object sender, EventArgs e) { Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("ID", 6); dic.Add("name", "王二麻子"); dic.Add("age", 44); dic.Add("address", "陜西"); int result = SQLiteHelpers.InsertData("student", dic); Console.WriteLine("插入結果,受影響的行數:" + result); } /// <summary> /// 修改數據 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Modify_Click(object sender, EventArgs e) { Dictionary<string, object> dic = new Dictionary<string, object>(); //將列名 name 的值改為 “猴子” dic.Add("name", "猴子"); //將列名 address 的值改為 花果山 dic.Add("address", "花果山"); //where條件 string where = "ID = @ID AND age = @Age"; //where條件中對應的參數 SQLiteParameter[] parameter = new SQLiteParameter[] { new SQLiteParameter("ID", 4), new SQLiteParameter("Age",23) }; int result = SQLiteHelpers.Update("student", dic, where, parameter); Console.WriteLine("修改結果,受影響的行數:" + result); } /// <summary> /// 刪除數據 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Delete_Click(object sender, EventArgs e) { //where條件 string where = "ID = @ID"; //where條件中對應的參數 SQLiteParameter[] parameter = new SQLiteParameter[] { new SQLiteParameter("ID", 6), }; int result = SQLiteHelpers.Delete("student", where, parameter); Console.WriteLine("刪除結果,受影響的行數:" + result); } /// <summary> /// 判斷表是否存在 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_TableExists_Click(object sender, EventArgs e) { string title = "dddd"; bool result = SQLiteHelpers.TableExists(title); Console.WriteLine(string.Format("{0} 表是否存在,結果:{1}", title, result)); } //輸出各表中的數據 //public static void PrintValues(DataSet ds) //{ // foreach (DataTable table in ds.Tables) // { // Console.WriteLine("表名稱:" + table.TableName); // foreach (DataRow row in table.Rows) // { // foreach (DataColumn column in table.Columns) // { // Console.Write(row[column] + ""); // } // Console.WriteLine(); // } // } //} } }
感謝你能夠認真閱讀完這篇文章,希望小編分享的“C#如何操作SQLite實現數據的增刪改查”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。