孜孜不倦的程序员:SQLite 内幕
2010-09-08 00:00:00 来源:WEB开发网本机开发
从一开始,SQLite 就立足于面向本机代码开发人员的数据库,这就是它为何作为本机 C/C++ DLL 实施的原因。 SQLite 这种本机特色的利弊鲜明:有利的是,它从执行指定 SQL 语句所需的总时间中省去了许多开销(例如穿过网络到达服务器,然后重新返回);而弊端在于,由于原始 SQLite 数据库是本机 C/C++ DLL,因此从基于 Microsoft .NET Framework 的应用程序访问它会是一项不小的挑战。
庆幸的是,技术精湛的 .NET Framework 开发人员认识到访问本机 DLL 实际上只是练习使用 P/Invoke 声明,而围绕 SQLite DLL 中公开的本机声明创建包装类则相对比较容易。 事实上,对于基本功能来说,就像开源社区中提供的众多内容一样,它们也已经实现;导航到 switchonthecode.com/tutorials/csharp-tutorial-writing-a-dotnet-wrapper-for-sqlite,我们会发现已创建好的 P/Invoke 声明的工作集,如图 1 中所示。
图 1 P/Invoke 声明
namespace SQLiteWrapper
{
public class SQLiteException : Exception
{
public SQLiteException(string message) :
base(message)
{ }
}
public class SQLite
{
const int SQLITE_OK = 0;
const int SQLITE_ROW = 100;
const int SQLITE_DONE = 101;
const int SQLITE_INTEGER = 1;
const int SQLITE_FLOAT = 2;
const int SQLITE_TEXT = 3;
const int SQLITE_BLOB = 4;
const int SQLITE_NULL = 5;
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_open")]
static extern int sqlite3_open(string filename, out IntPtr db);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_close")]
static extern int sqlite3_close(IntPtr db);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_prepare_v2")]
static extern int sqlite3_prepare_v2(IntPtr db, string zSql,
int nByte, out IntPtr ppStmpt, IntPtr pzTail);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_step")]
static extern int sqlite3_step(IntPtr stmHandle);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_finalize")]
static extern int sqlite3_finalize(IntPtr stmHandle);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_errmsg")]
static extern string sqlite3_errmsg(IntPtr db);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_count")]
static extern int sqlite3_column_count(IntPtr stmHandle);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_origin_name")]
static extern string sqlite3_column_origin_name(
IntPtr stmHandle, int iCol);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_type")]
static extern int sqlite3_column_type(IntPtr stmHandle, int iCol);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_int")]
static extern int sqlite3_column_int(IntPtr stmHandle, int iCol);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_text")]
static extern string sqlite3_column_text(IntPtr stmHandle, int iCol);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_double")]
static extern double sqlite3_column_double(IntPtr stmHandle, int iCol);
}
}
更多精彩
赞助商链接