PC軟體開發技術之三:C#操作SQLite資料庫
我們在開發應用是經常會需要用到一些資料的儲存,儲存的方式有多種,使用資料庫是一種比較受大家歡迎的方式。但是對於一些小型的應用,如一些移動APP,通常的資料庫過於龐大,而輕便的SQLite則能解決這一問題。不但操作方便,而且只需要要一個檔案即可,在這裡我們來說一說使用C#語言操作SQLite資料庫。
1、SQLite簡介
SQLite,是一款輕型的資料庫,是遵守ACID的關係型資料庫管理系統,它包含在一個相對小的C庫中。它是D.RichardHipp建立的公有領域專案。它的設計目標是嵌入式的,而且目前已經在很多嵌入式產品中使用了它,它佔用資源非常的低,在嵌入式裝置中,可能只需要幾百K的記憶體就夠了。它能夠支援Windows/Linux/Unix等等主流的
如果想了解更多關於SQLite的問題,可以訪問它的官方網站:http://www.sqlite.org/
2、開始前的準備
在開始之前我們需要準備必要的開發環境,這次咱們使用的是Visual Studio 2015開發環境,但是我們開發基於SQLite的應用光有VS2015還不夠。我需要到SQLite的官方網站下載並安裝SQLite。
在SQLite官網找到下載,有應用於各種環境的SQLite元件及原始碼,我們選擇Precompiled Binaries for .NET
3、C#操作SQLite的封裝
在完成開發環境的準備之後,我們接下來實現對SQLite操作的必要封裝,以進一步降低在具體應用中的使用難度。在這裡我們只是封裝一些常用而且必要的功能。
public class SQLiteHelper
{
//建立資料庫檔案
public static void CreateDBFile(string fileName)
{
string path = System.Environment.CurrentDirectory + @"/Data/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string databaseFileName = path + fileName;
if (!File.Exists(databaseFileName))
{
SQLiteConnection.CreateFile(databaseFileName);
}
}
//生成連線字串
private static string CreateConnectionString()
{
SQLiteConnectionStringBuilder connectionString = new SQLiteConnectionStringBuilder();
connectionString.DataSource = @"data/ScriptHelper.db";
string conStr = connectionString.ToString();
return conStr;
}
/// <summary>
/// 對插入到資料庫中的空值進行處理
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object ToDbValue(object value)
{
if (value == null)
{
return DBNull.Value;
}
else
{
return value;
}
}
/// <summary>
/// 對從資料庫中讀取的空值進行處理
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object FromDbValue(object value)
{
if (value == DBNull.Value)
{
return null;
}
else
{
return value;
}
}
/// <summary>
/// 執行非查詢的資料庫操作
/// </summary>
/// <param name="sqlString">要執行的sql語句</param>
/// <param name="parameters">引數列表</param>
/// <returns>返回受影響的條數</returns>
public static int ExecuteNonQuery(string sqlString, params SQLiteParameter[] parameters)
{
string connectionString=CreateConnectionString();
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlString;
foreach (SQLiteParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 執行查詢並返回查詢結果第一行第一列
/// </summary>
/// <param name="sqlString">SQL語句</param>
/// <param name="sqlparams">引數列表</param>
/// <returns></returns>
public static object ExecuteScalar(string sqlString, params SQLiteParameter[] parameters)
{
string connectionString = CreateConnectionString();
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlString;
foreach (SQLiteParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteScalar();
}
}
}
/// <summary>
/// 查詢多條資料
/// </summary>
/// <param name="sqlString">SQL語句</param>
/// <param name="parameters">引數列表</param>
/// <returns>返回查詢的資料表</returns>
public static DataTable GetDataTable(string sqlString,params SQLiteParameter[] parameters)
{
string connectionString = CreateConnectionString();
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlString;
foreach (SQLiteParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
DataSet ds = new DataSet();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(ds);
return ds.Tables[0];
}
}
}
}
4、應用例項
上面封裝完了之後,我們就是使用上面封裝的函式來實際操作SQLite資料庫。對資料庫的應用例項無非就是對各種物件的增、刪、改、查。我沒列舉一個對原始碼型別物件的各種操作例項如下:
public class ScriptTypeDAL
{
public ScriptTypeM ToScriptType(DataRow row)
{
ScriptTypeM type = new ScriptTypeM();
type.ScriptTypeId = (Guid)row["ScriptTypeId"];
type.ScriptType = (string)row["ScriptType"];
type.IsUsing = (bool)row["IsUsing"];
return type;
}
public void Insert(ScriptTypeM Type)
{
SQLiteHelper.ExecuteNonQuery(@"insert into TB_ScriptType(ScriptTypeId,ScriptType,IsUsing)
Values(@ScriptTypeId,@ScriptType,1)",
new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId),
new SQLiteParameter("ScriptType", Type.ScriptType));
}
public void Update(ScriptTypeM Type)
{
SQLiteHelper.ExecuteNonQuery(@"update TB_ScriptType set [email protected],
[email protected] where [email protected]",
new SQLiteParameter("ScriptType", Type.ScriptType),
new SQLiteParameter("IsUsing", Type.IsUsing),
new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId));
}
public ScriptTypeM GetbyId(Guid id)
{
DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where ScriptTypeId[email protected]",
new SQLiteParameter("id", id));
if (table.Rows.Count <= 0)
{
return null;
}
else if (table.Rows.Count > 1)
{
throw new Exception("Id重複!");
}
else
{
return ToScriptType(table.Rows[0]);
}
}
public ScriptTypeM GetbyName(string name)
{
DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where [email protected]",
new SQLiteParameter("name", name));
if (table.Rows.Count <= 0)
{
return null;
}
else if (table.Rows.Count > 1)
{
throw new Exception("型別名稱重複!");
}
else
{
return ToScriptType(table.Rows[0]);
}
}
public ScriptTypeM[] ListAll()
{
DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where IsUsing=1");
ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];
for (int i = 0; i < table.Rows.Count; i++)
{
type[i] = ToScriptType(table.Rows[i]);
}
return type;
}
public ScriptTypeM[] Search(string sql, List<SQLiteParameter> parameterList)
{
DataTable table = SQLiteHelper.GetDataTable(sql, parameterList.ToArray());
ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];
for (int i = 0; i < table.Rows.Count; i++)
{
type[i] = ToScriptType(table.Rows[i]);
}
return type;
}
}
SQLite資料庫小巧而且應用方便,在一些小型應用和嵌入式應用中很有優勢,當然如何應用的得心應手就看個人了。
歡迎關注: