1、通過Add References引用SQLite ADO .NET安裝目錄的bin目錄下的System.Data.SQLite.DLL。
2、創建數據庫文件:因為始終是個0字節文件,應該利用IO也可以(?!)。
System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
3、連接數據庫
System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(connectionString);
connectionString中包含了數據庫的一些配置信息,比如數據庫文件,數據庫打開的密碼等,可以利用System.Data.SQLite.SQLiteConnectionStringBuilder來輔助創建connectionString
4、創建表、讀取數據等和Access或MS SQL沒多大區別了。
//創建一個數據庫文件
string datasource="h:/test.db";
System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
//連接數據庫
System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
connstr.DataSource = datasource;
connstr.Password = "admin";//設置密碼,SQLite ADO.NET實現了數據庫密碼保護
conn.ConnectionString = connstr.ToString();
conn.Open();
//創建表
System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
string sql = "CREATE TABLE test(username varchar(20),password varchar(20))";
cmd.CommandText=sql;
cmd.Connection=conn;
cmd.ExecuteNonQuery();
//插入數據
sql = "INSERT INTO test VALUES(’dotnetthink’,mypassword’)";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
//取出數據
sql = "SELECT * FROM test";
cmd.CommandText = sql;
System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.Append("username:").Append(reader.GetString(0)).Append("
")
.Append("password:").Append(reader.GetString(1));
}
MessageBox.Show(sb.ToString());