1.以操作SQLite為例.先下載Dapper,項目引用添加Dapper.dll,然后入下
SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder(); sb.DataSource = @"D:sqlite.db"; SQLiteConnection con = new SQLiteConnection(sb.ToString()); con.Open(); string sql = "select * from user"; foreach( User u in con.Query<User>(sql)) { Console.WriteLine(u.Name); } con.Close();
參數查詢:
SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder(); sb.DataSource = @"D:\\sqlite.s3db"; SQLiteConnection con = new SQLiteConnection(sb.ToString()); con.Open(); var data = con.Query("select * from t_session where appkey=@appkey", new { appkey = appKey }); con.Close();
添加:
con.Execute(" insert into t_session(appkey,appsecret,updatetime)values(@appkey,@appsecret,@updatetime)" , new { appkey = appKey, appsecret = appSecret, updatetime = DateTime.Now });
更新:
//更新 con.Execute("update t_session set appsecret=@appsecret where appKey=@appKey ", new { appKey = appKey, appsecret = appSecret });
今天學習用Sqlite結果總出錯:no such table: MyFriendInfo
翻譯一下就是:沒有找到MyFriendInfo表。
怎么會這樣呢?在數據庫里面明明有表的。
調試和查看原文件各級目錄發現:
當Sqlite找不到相關的表的時候會自動創建。這下可明白了。問題出在路徑上。
我在App.Config文件中是這樣寫的
- <appSettings>
- <add key="SqlConfiguration" value="Data Source= |DataDirectory|\MyFriendList.sqlite; Integrated Security='True'"/>
- </appSettings>
|DataDirectory| 的作用是定位到App_Data文件夾下面,源程序則是生成在\bin\Debug\目錄下面,結果在Debug目錄下面發現了Sqlite自動生成的數據庫。這下明白了。不過在做WINFORM程序的時候如果還要安裝,那數據庫路徑在Config文件中是不能寫死的。放在Debug目錄下面應該是一個解決辦法吧。
如果是WEB應用程序這個問題就好解決了。