C#/Java连接sqlite与使用技巧
1)下载sqlite jdbc驱动
2)将下载的驱动加入eclipse项目的built path中
3)示例代码:
package com.hedalixin;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.statement;
public class test {
/**
* @param args
*/
public static void main(string[] args) throws exception {
// todo auto-generated method stub
class.forname("org.sqlite.jdbc");
connection conn = drivermanager.getconnection("jdbc:sqlite:test.db");
statement stat = conn.createstatement();
stat.executeupdate("drop table if exists people;");
stat.executeupdate("create table people (name, occupation);");
preparedstatement prep = conn
.preparestatement("insert into people values (?, ?);");
prep.setstring(1, "gandhi");
prep.setstring(2, "politics");
prep.addbatch();
prep.setstring(1, "turing");
prep.setstring(2, "computers");
prep.addbatch();
prep.setstring(1, "wittgenstein");
prep.setstring(2, "smartypants");
prep.addbatch();
conn.setautocommit(false);
prep.executebatch();
conn.setautocommit(true);
resultset rs = stat.executequery("select * from people;");
while (rs.next()) {
system.out.println("name = " + rs.getstring("name"));
system.out.println("job = " + rs.getstring("occupation"));
}
rs.close();
conn.close();
}
}
2. c#连接sqlite
2.1 使用sqlite.net
sqlite.net也是一个数据访问组件,其中的system.data.sqlite 就好像是.net自带的system.data.sqlclient一样。里面包含了connection、command等数据访问的常用对象,只是他们前面都有一个前缀sqlite。
1)下载system.data.sqlite,下载地址
2) 通过add references引用sqlite ado .net安装目录的bin目录下的system.data.sqlite.dll。
3)创建表、读取数据等和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('ekinglong','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("\n")
.append("password:").append(reader.getstring(1));
}
messagebox.show(sb.tostring());
2.2使用原生态的ado.net访问sqlite
using (dbconnection conn = new sqliteconnection( system.configuration.configurationmanager.connectionstrings["sqlite"].connectionstring))
{
conn.open();
dbcommand comm = conn.createcommand();
comm.commandtext = "select * from customer";
comm.commandtype = commandtype.text;
using (idatareader reader = comm.executereader())
{
while (reader.read())
{
response.write(reader[0]);
}
}
}
sqlite.net数据库连接字符串connectionstring格式:
basic(基本的)
data source=filename;version=3;
using utf16(使用utf16编码)
data source=filename;version=3;useutf16encoding=true;
with password(带密码的)
data source=filename;version=3;password=mypassword;
using the pre 3.3x database format(使用3.3x前数据库格式)
data source=filename;version=3;legacy format=true;
read only connection(只读连接)
data source=filename;version=3;read only=true;
with connection pooling(设置连接池)
data source=filename;version=3;pooling=false;max pool size=100;
using datetime.ticks as datetime format()
data source=filename;version=3;datetimeformat=ticks;
the default value is iso8601 which activates the use of the iso8601 datetime format
store guid as text(把guid作为文本存储,默认是binary)
data source=filename;version=3;binaryguid=false;
如果把guid作为文本存储需要更多的存储空间
specify cache size(指定cache大小)
data source=filename;version=3;cache size=2000;
cache size 单位是字节
specify page size(指定页大小)
data source=filename;version=3;page size=1024;
page size 单位是字节
disable enlistment in distributed transactions
data source=filename;version=3;enlist=n;
disable create database behaviour(禁用创建数据库行为)
data source=filename;version=3;failifmissing=true;
默认情况下,如果数据库文件不存在,会自动创建一个新的,使用这个参数,将不会创建,而是抛出异常信息
limit the size of database(限制数据库大小)
data source=filename;version=3;max page count=5000;
the max page count is measured in pages. this parameter limits the maximum number of pages of the database.
disable the journal file (禁用日志回滚)
data source=filename;version=3;journal mode=off;
this one disables the rollback journal entirely.
persist the journal file(持久)
data source=filename;version=3;journal mode=persist;
this one blanks and leaves the journal file on disk after a commit. default behaviour is to delete the journal file after each commit.
controling file flushing
data source=filename;version=3;synchronous=full;
full specifies a full flush to take action after each write. normal is the default value. off means that the underlying os flushes i/o's.
sqlite使用技巧
1 .sqlite判断数据表是否存在
select count(*) as cnt from sqlite_master where type='table' and name='dbinfo' //其中dbinfo为需要判断的表名。注意大小写敏感!
2. sqlite一条sql语句插入多条记录
insert into table(col1, col2) select val11, val12 union all select val21, val22 ;
这样的写法是属于复合sql语句,表示先把两个select的结果集进行无删减的联合,再把联合结果插入到table中。
3. sqlite事务
是以文件的形式存在磁盘中,每次访问时都要打开一次文件,如果对数据进行大量操作时,会很慢~
解决办法是用事务的形式提交:因为我们开始事务后,进行大量操作的语句都保存在内存中,当提交时才全部写入数据库,此时,数据库文件也就只用打开一次。
sql语句:
begin;
insert into "table" values ('a', 'b', 'c');
insert into "table" values ('a', 'b', 'c');
insert into "table" values ('a', 'b', 'c');
commit;
4. sqlite自增id字段使用方法为 integer primary key autoincrement
5. 分页查询显示
类似mysql数据库 ,是利用mysql的limit函数,limit [offset,] rows从数据库表中m条记录开始检索n条记录的语句为:
select * from 表名称 limit m,n
例如从表sys_option(主键为sys_id)中从10条记录开始检索20条记录,语句如下:
select * from sys_option limit 10,20