恰好开发一个winform程序,希望在客户端存储一些信息,在离线状态下也能够同步数据库。本来解决方案是在本地采用xml 文件进行存储数据,也很好实现,但是xml文件操作起来没有数据库那么方便,于是就更改了解决方案,采用SQLLite这个轻量级数据库。
1. 软件工具:visual studio 2008 框架:NET framework 3.5
2. 数据库的部署,
sqllite下载地址:tp://sourceforge.net/projects/sqlite-dotnet2/files/SQLite%20for%20ADO.NET%202.0/1.0.66.0/SQLite-1.0.66.0-setup.exe/download
点击下载后,安装就行。(注意:安装的时候最好不要开着vs2008)
3. 打开vs2008,新建一个winform应用程序
4. 打开“服务器资源管理器” 在这里右击“数据连接”---->添加连接 ------》更改 -----》更改数据源为:“SQLLite Database FIle“----->确定 ---->Browse选择你的数据库,(注意选择的文件一定是以后缀“.db3”结束的,如果你还没建库,那么你就随便建一个以后缀为"db3"结束的文件,放到你项目的bin目录的debug中(很重要,程序发布的路径))
5.OK,SQLLite已经建好了,可以在vs2008中用图形化界面操作我们的SQLLite库了,这是多么棒的事情。
6.右击项目名称 ---- >>> 添加引用---> 添加System.data.SQLite (如果要用LinQ,把System.data.SQLite.Linq也添上)
7.ok,可以编写代码操作SQLLite数据库了。新建“SqlLiteHelper.cs”类
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Data;
using
System.Data.SQLite;
//
需要添加
using
System.Windows.Forms;
//
需要添加
namespace
Client
{
class
SqlLiteHelper
{
#region
连接字符串
///
<summary>
///
连接数据库字符串
///
</summary>
///
<returns></returns>
public
static
String getSQLiteConn()
{
return
"
Data Source=
"
+
Application.StartupPath
+
"
\\statistics.db3
"
;
//获取绝对路径,看好了,别搞错了
}
#endregion
public
static
void
insert(String ip)
{
SQLiteConnection conn
=
new
SQLiteConnection(SqlLiteHelper.getSQLiteConn());
SQLiteCommand cmd
=
new
SQLiteCommand();//很熟悉把
DateTime StartComputerTime
=
DateTime.Now;
cmd.Connection
=
conn;
cmd.CommandText
=
"
insert into TimeBill(id,ip,StartComputerTime,logoutTime) values(@id ,@ip,@StartComputerTime,0)
"
;
cmd.Parameters.AddWithValue(
"
@ip
"
, ip);
cmd.Parameters.AddWithValue(
"
@id
"
,
1
);
cmd.Parameters.AddWithValue(
"
@StartComputerTime
"
, StartComputerTime.ToString());
using
(conn)
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
}
复制代码
8.ok。如果出现异常为“no such table”,那么错误一定出在路径上,路径一定是绝对路径。
“no such table ”直译为“找不到表”,原来SQLLite在定义的路径下找不到数据库时,它会自动建设一个空的SQLLite库,那么找到的就是这个空库,自然就没有表了,所以就会报告“no such table "的错误。解决办法:仔细修改路径。
注意:编写SQLLite的sql语句时,只有部分sql函数在SQLLite中可以用,目前用到的getdate()函数不能用。
些此文目的:希望能为初学者节省点时间!弯路必不可少,我们慢慢走过,体验编程之快!