Sqlite资料收集

SQLite简单教程

http://www.cnblogs.com/wildfish/archive/2006/03/25/358532.html

最早使用SQLite是因为sql2005实在是重量了,我的老机器跑的咯吱咯吱了。
而且,Access用得不习惯--指的是.Net的访问。
后来Cnblogs搜索了一下,觉得SQLite不错,因为我的框架本身没有使用存储过程。
废话不多说,言归正传。
1。从www.sqlite.org下载SQLite 3.3.4的版本
   为了方便,我把它解压了,就一个SQLite3.exe,放入Windows目录下。
   Cmd 进入命令行
   1)
   创建数据库文件:
   >SQLite3 d:\test.db 回车
   就生成了一个test.db在d盘。
   这样同时也SQLite3挂上了这个test.db
   2)
   用.help可以看看有什么命令
   >.help 回车即可
   3)可以在这里直接输入SQL语句创建表格 用;结束,然后回车就可以看到了
   4)看看有创建了多少表
   >.tables
   5)看表结构
   >.schema 表名
   6)看看目前挂的数据库
   >.database
   7)如果要把查询输出到文件
   >.output 文件名
   > 查询语句;
   查询结果就输出到了文件c:\query.txt

   把查询结果用屏幕输出
   >.output stdout

   8)把表结构输出,同时索引也会输出
     .dump 表名
   9)退出
   >.exit 或者.quit

2。从http://sqlite.phxsoftware.com/下载Ado.net驱动。
   下载了安装,在安装目录中存在System.Data.SQLite.dll
    我们只需要拷贝这个文件到引用目录,并添加引用即可对SQLite数据库操作了
   所有的Ado.net对象都是以SQLite开头的,比如SQLiteConnection
   连接串只需要如下方式
   Data Source=d:\test.db 或者DataSource=test.db--应用在和应用程序或者.net能够自动找到的目录
   剩下的就很简单了~~

3。SQL语法
   由于以前用SQLServer或者ISeries,所以DDL的语法很汗颜
   1)创建一个单个Primary Key的table
   CREATE TABLE  [Admin] (
[UserName] [nvarchar] (20)   PRIMARY KEY NOT NULL ,
[Password] [nvarchar] (50)   NOT NULL ,
[Rank] [smallint] NOT NULL ,
[MailServer] [nvarchar] (50)   NOT NULL ,
[MailUser] [nvarchar] (50)   NOT NULL ,
[MailPassword] [nvarchar] (50)   NOT NULL ,
[Mail] [nvarchar] (50)   NOT NULL
   ) ;
   2)创建一个多个Primary Key的table
   CREATE TABLE  [CodeDetail] (
[CdType] [nvarchar] (10)  NOT NULL ,
[CdCode] [nvarchar] (20)  NOT NULL ,
[CdString1] [ntext]   NOT NULL ,
[CdString2] [ntext]   NOT NULL ,
[CdString3] [ntext]   NOT NULL,
  PRIMARY KEY (CdType,CdCode)
   ) ;
   3)创建索引
   CREATE  INDEX [IX_Account] ON  [Account]([IsCheck], [UserName]);
   还可以视图等等。
4.还有很有用的SQL
  Select * from Sqlite_master
  Select datetime('now')
  Select date('now')
  Select time('now')
  以及很多函数,具体可以参考SQLite的wiki.
oh,还有就是看到有人说,好像成批插入的时候,启动事务,比不启动事务快n倍
还有就是尽量使用参数化的SQL,估计和商用DB一样能够自动Prepare.

===========

sqlite可以在shell/dos command底下直接执行命令:
sqlite3 film.db "select * from film;"     (我在执行的时候发现回车后要输入go)
输出 HTML 表格:
sqlite3 -html film.db "select * from film;"
将数据库「倒出来」:
sqlite3 film.db ".dump" > output.sql
利用输出的资料,建立一个一模一样的数据库(加上以上指令,就是标准的SQL数据库备份了):
sqlite3 film.db < output.sql
在大量插入资料时,你可能会需要先打这个指令:
begin;
插入完资料后要记得打这个指令,资料才会写进数据库中:
commit;

;

SQLite——只要3分钟,你就可以在.NET上创建和运行它 -------------转载

SQLite是一个开源数据库,现在已变得越来越流行,它的体积很小,被广泛应用于各种不同类型的应用中。

什么是SQLite?

SQLite的官方网站上是这样定义SQLite的:

SQLite是一个软件库,用于实现自包含非服务式零配置事务化的SQL数据库引擎。
SQLite 是一个嵌入式SQL数据库引擎,与其它大多数SQL数据库不同的是,SQLite没有独立的服务进程。SQLite直接读写原始的磁盘文件,一个拥有多个 表、索引、触发器和视图的完整SQL数据库就包含在一个独立的磁盘文件中。数据库文件的格式是跨平台的,你可以在32位和64位系统之间、甚至在Big-EndianLittle-Endian(译者注:这是两种不同的字节排序方式,Big-Endian是指一个word中的高位Byte是放在内存word区域的低地址处,而Little-Endian则与之相反)两种不同的架构间自由地拷贝数据库,这一特性让SQLite成为应用文件格式的一种流行选择。SQLite不能替代Oracle,但可以考虑作为fopen()的替代方法。
SQLite已经是世界上布署得最广泛的SQL数据库引擎,被用在无以计数的桌面电脑应用中,还有消费电子设备中,如移动电话、掌上电脑和MP3播放器等。SQLite的源码就放在公有领域(即WikiPedia的public domain)中。

SQLite最早是应用在Linux和OSX平台上的,但对数据库需求较少的Windows应用而言,它是替代SQL Express和Access数据库运行于.NET之上的一个可行且实用的选择。

有一篇来自开发者Mike Duncan的文章,给出了一个在3分钟内就可将SQLite安装到.NET上的指南。这个指南非常有用,读完它你就可以使用一个轻量级的数据库来处理你丢给它的许多任务。

3分钟的指南

指南是从第一次下载SQLite开始的:

尽管你可以通过SQLite下载页获得Windows的通用库,但我还是打算建议你从sourceforge获取SQLite的ADO.NET 2.0数据提供者,我并不是说它是最高效的版本(它有一个ADO包装层以及附带的无用功能),但它确实是一个非常容易上手的版本,可能值得长期使用。

找出DLL:

将找到的DLL(System.Data.SQLite.DLL)拷贝到你的项目中,并添加引用。

下载和安装一个SQLite GUI工具,SQLiteMan有一个非常出色的windows版本,指南上是这样说的:

我一直在使用的工具名为“SQLite Administrator”(很合适的名字,它是免费的!)有一个“甜点”——有着一个和Query Analyzer很像的界面。如果你有兴趣的话,可以从这里http://www.sqlite.org/cvstrac/wiki?p=ManagementTools找到一个很大的SQLite GUI客户端列表。

指南的最后一步就是创建一个SQLite数据库:

通过GUI,创建一个数据库并随意创建一个测试表,就会出现一个以.s3db为尾缀的单独文件。

一旦System.Data.SQLite.dll被引用为.NET项目的一部分,那就可以像在你的应用顶部写using System.Data.SQLite那样容易地使用它。通过使用ADO.NET包装层,一个参数化的查询看上去会像是这样:

string lookupValue;
using (SQLiteCommand cmd = cnn.CreateCommand())

{
for (int i = 0; i < 100; i++)


{
lookupValue = getSomeLookupValue(i);


cmd.CommandText = @"UPDATE [Foo] SET [Value] = [Value] + 1


WHERE [Customer] LIKE '" + lookupValue + "'";


cmd.ExecuteNonQuery();



}
}
数据提供者

SQLite已经实实在在地影响到.NET的开发,已经有很多数据提供器被用于流行的对像关系映射(O/RM, 即Object-Relational Mapper)框架中。

LINQ提供器允许.NET 3.5的开发者们利用新LINQ框架的优势,并以SQLite作为后端数据存储。

SQLite可以作为替代Access或SQL Express让数据库应用快速创建和运行起来的一个不错选择,而且因为数据库还可以同时在Linux和Mac OSX平台上使用,所以创建一个可以跨平台使用的数据库应用很容易。

查看英文原文Up and Running with SQLite on .NET in 3 Minutes

 

SQLite外键的实现

http://www.sqlite.com.cn/MySqlite/6/403.Html

 

SQLite现在的版本还不支持外键功能,虽然外键约束会被解析,但执行的时候被忽略。但我们可以手动实现外键,实现的原理就是触发器。下面是我的实现方法。主要是针对一个例子:
先看下面两个表。
CREATE TABLE PLU (PluID integer NOT NULL PRIMARY KEY,
                   Name text NOT NULL,
                   Property text,
                   Price double NOT NULL,
                   Left integer NOT NULL,
                   Department text,
                   Other text);

CREATE TABLE PluSuit (SuitID integer NOT NULL PRIMARY KEY,
                     Price double NOT NULL,
                     Property text,
                     Name text NOT NULL,
                     PluID integer NOT NULL CONSTRAINT fk_plu_id REFERENCES PLU(PluID) ON DELETE CASCADE,
                     Numbers integer NOT NULL)
这样就为PluSuit表建立对PLU表的外键约束,这样就可以实现CORE2数据需求中的要求,问题是SQLite不执行这个约束,所以这样创建以后,我们还要再创建三个触发器,INSERT,UPDATE,DELETE触发器:

BEFORE INSERT ON PluSuit
  FOR EACH ROW BEGIN
      SELECT RAISE(ROLLBACK, 'insert on table "PluSuit" violates foreign key constraint "fk_plu_id"')
      WHERE  (SELECT PluID FROM PLU WHERE PluID = NEW.PluID) IS NULL;
  END;

BEFORE UPDATE ON PluSuit
  FOR EACH ROW BEGIN
      SELECT RAISE(ROLLBACK, 'update on table "PluSuit" violates foreign key constraint "fk_plu_id"')
      WHERE  (SELECT PluID FROM PLU WHERE PluID = NEW.PluID) IS NULL;
  END;

CREATE TRIGGER fkd_plusuit_pluid
BEFORE DELETE ON PLU
FOR EACH ROW BEGIN
      DELETE from PluSuit WHERE PluID = OLD.PluID;
END;

下面我们分别来作三个实验:
一、插入实验
首先我们在PLU里面插入一个数据(一双anta运动鞋的信息):
insert into PLU values(1,'anta','sport',299,100,'sales','ok');
insert into PLU values(3,'nike','sport',699,200,'sales','ok');
然后我们开始在PluSuit里面插入一个数据(两双一起打折卖):
insert into PluSuit values(100,350,'old','anta',1,2);成功了
insert into PluSuit values(100,350,'old','anta',2,2);失败,得到正确的错误信息

更新实验
update PluSuit set PluID=2 where SuitID=100;失败,得到正确的错误信息
update PluSuit set PluID=3 where SuitID=100;成功

删除实验
delete from PLU where PluID=1;
查看PluSuit中数据被正确删除。
实验结果,触发器的实现完全正确。

 

Using SQLite with Enterprise Library 3.1

http://www.eggheadcafe.com/tutorials/aspnet/ba7ea7a0-4e67-4863-941c-f4dadf9b7127/aspnet-using-sqlite-wit.aspx

Information and download of System.Data.SqLite:
http://sqlite.phxsoftware.com/

Enterprise Library 3.1 (May 2007):
http://www.microsoft.com/downloads/details.aspx?FamilyID=4c557c63-708f-4280-8f0c-637481c31718&displaylang=en

EntLibContrib Project at codeplex:
http://www.codeplex.com/entlibcontrib

I've extolled the virtues of the amazing SQLite database engine a number of times here (just use our Search widget with "SQLITE") so I won't go into much detail about it. Here are a few bullet points, though:

  1. Complete ADO.NET 2.0 Implementation
  2. Supports the Full and Compact .NET Framework as well as native C/C++
  3. Completely portable database files
  4. Incredibly fast, faster than most every other embedded database, including Sql Server Mobile
  5. Encryption Support
  6. Full Text Search
  7. Visual Studio 2005 Design-Time Support
  8. Single file redistributable under 500kb -- nothing to "install"!
  9. Extensive SQL support
  10. User-Defined Functions & Collating Sequences, Triggers
  11. Full Source Included.  100% Free

You can thank my friend Robert Simpson for all this effort and contribution. In sum, SQLite is very fast, requires no configuration  or installation (only that the assembly be present), and implements most all of the SQL 92 spec. With the ADO.NET Provider, you are dealing with datareaders, DataSets and all the familiar programming tools you are used to. The SQL syntax is a bit of a variant from T-SQL, but the differences are quite minor.
At Codeplex, there is a Enterprise Library "contrib" project with a number of enhancements written by users like you and me. One in particular that caught my attention was the SQLite provider, written by Ken Scott  http://freqken.net/.

The solution here shows how to wire up your Entlib configuration to use the ADO.NET 2.0 System.Data.SqLite engine with Enterprise Library 3.1

First you will need the required EntLib and Contrib assemblies:

Microsoft.Practices.EnterpriseLibrary.Data
Microsoft.Practices.EnterpriseLibrary.Common
EnterpriseLibrary.Contrib.Data.SqLite
EnterpriseLibrary.Contrib.Data

Then, you'll set up your configuration, which can be done with the EntLib Configuration Add-on from within Visual Studio:

My sample config looks like this:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
  <dataConfiguration defaultDatabase="ConnectionString">
    <providerMappings>
      <add databaseType="Microsoft.Practices.EnterpriseLibrary.Contrib.Data.SqLite, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        name="System.Data.SqLite" />
    </providerMappings>
  </dataConfiguration>
  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=dbpath;New=True;UTF8Encoding=True;Version=3"
      providerName="System.Data.SQLite" />
  </connectionStrings>
  <appSettings>
    <add key="Setting" value="" />
  </appSettings>
  <system.web>  
    <compilation debug="true" />   
    <authentication mode="Windows" />   
  </system.web>
</configuration>




Finally, I've got two sample classes that I ripped right out of the test fixtures from the Contrib project, and massaged to fit this demo:

using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;

namespace  SQLiteEntLib 
{
    public class TestConfigurationSource
    {
        public static DictionaryConfigurationSource CreateConfigurationSource()
        {
            DictionaryConfigurationSource source = new DictionaryConfigurationSource();
            DatabaseSettings settings = new DatabaseSettings();
            settings.DefaultDatabase = "Quotes";
            ConnectionStringsSection section = new ConnectionStringsSection();
            string dbPath = System.Web.HttpContext.Current.Server.MapPath("quotes.db3");
            section.ConnectionStrings.Add(new ConnectionStringSettings("ConnectionString", @"Data Source=" + dbPath , "System.Data.SQLite"));
            source.Add(DatabaseSettings.SectionName, settings);
            source.Add("connectionStrings", section);
            return source;
        }
    }
}



using System;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace SQLiteEntLib 
{
    public class SQLiteExecuteDatasetHelper
    {
        private const string queryString = "Select * from quotes where authorname like 'a%'";
        private Database db;
        
        public DataSet  ExecuteDataSetFromSqlString()
        {
            DatabaseProviderFactory factory = new DatabaseProviderFactory(TestConfigurationSource.CreateConfigurationSource());
            db = factory.Create("ConnectionString");
            DataSet dataSet = db.ExecuteDataSet(CommandType.Text, queryString);
            return dataSet;
        }
    }
}

And that's it! The Database object has most of the same familiar methods that are present for all the other Providers. The only thing you don't have is stored procedures.

However, based on all the "stored procs are evil" diatribe I've listened to and read, that could be a good thing!

Note that I am doing a string Replace on the "dbPath" string with Server.MapPath and the name of the database file to make this more portable for ASP.NET.
The download has a small SQLite database of quotations by famous authors (a subset, for size) and the ASP.NET app displays the results of a query in a GridView. You can run this without downloading anything as it already contains all the required assemblies. Just unzip, load into Visual Studio 2005, and press the green button!
Of course, I recommend that you download the three projects and sources from the links at the very top of this article and install each so you can look at code and learn more.

 

如果得到这个错误“

Unable to find the requested .Net Framework Data Provider.  It may not be installed.


给config文件添加下边配置。

<configuration> 
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite"/>
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite"
type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
</configuration>

 

工具

SQLite Administrator

http://download.orbmu2k.de/download.php?id=19

如果你使用的是sqllite3,那么你应该使用一下SqliteAdmin的一个”更新到sqlite3”的功能。

SQLite Expert

http://www.sqliteexpert.com/download.html

使用中发现SqliteAdmin做出来的中文数据,在.net访问时候是乱码(虽然用sqlitecommand查出来的时候没有问题),后来在网上检索发现如下:

关于SQLite乱码问题解决办法(界面乱码、插入数据后管理工查询乱码)
1、更换创建数据库工具,由原来的 SQLite Administrator 改成 SQLite Expert Professional,创建数据库时选择编码为UTF8。
2、"Data Source=DBName;New=False;Compress=True;Synchronous=Off;UTF8Encoding=True;Version=3" 同样注意UTF8Encoding 标

识改为True。
3、SQLLite Expert ,Tools菜单、Options、General项中、Encoding组,选中UTF-8。

 SQLite不支持的SQL语法总结

http://hi.baidu.com/83925com/blog/item/7f430b366e305bd7a3cc2b90.html

1 TOP
这是一个大家经常问到的问题,例如在SQLSERVER中可以使用如下语句来取得记录集中的前十条记录:
SELECT TOP 10 * FROM [index] ORDER BY indexid DESC;
但是这条SQL语句在SQLite中是无法执行的,应该改为:
SELECT * FROM [index] ORDER BY indexid DESC limit 0,10;
其中limit 0,10表示从第0条记录开始,往后一共读取10条

2 创建视图(Create View)
SQLite在创建多表视图的时候有一个BUG,问题如下:
CREATE VIEW watch_single AS SELECT DISTINCTwatch_item.[watchid],watch_item.[itemid] FROM watch_item;
上面这条SQL语句执行后会显示成功,但是实际上除了
SELECT COUNT(*) FROM [watch_single ] WHERE watch_ single.watchid = 1;
能执行之外是无法执行其他任何语句的。其原因在于建立视图的时候指定了字段所在的表名,而SQLite并不能正确地识别它。所以上面的创建语句要改为:
CREATE VIEW watch_single AS SELECT DISTINCT [watchid],[itemid] FROM watch_item;
但是随之而来的问题是如果是多表的视图,且表间有重名字段的时候该怎么办?

3 COUNT(DISTINCT column)
SQLite在执行如下语句的时候会报错:
SELECT COUNT(DISTINCT watchid) FROM [watch_item] WHERE watch_item.watchid = 1;
其原因是SQLite的所有内置函数都不支持DISTINCT限定,所以如果要统计不重复的记录数的时候会出现一些麻烦。比较可行的做法是先建立一个不重复的记录表的视图,然后再对该视图进行计数。

4 外连接
虽然SQLite官方已经声称LEFT OUTER JOIN 已经实现,但还没有 RIGHT OUTER JOIN 和 FULL OUTER JOIN。但是实际测试表明似乎并不能够正常的工作。以下三条语句在执行的时候均会报错:
SELECT tags.[tagid] FROM [tags],[tag_rss] WHERE tags.[tagid] = tag_rss.[tagid](*);
SELECT tags.[tagid] FROM [tags],[tag_rss] WHERE LEFT OUTER JOIN tag_rss.[tagid] = tags.[tagid];
SELECT tags.[tagid] FROM [tags],[tag_rss] WHERE LEFT JOIN tag_rss.[tagid] = tags.[tagid];
此外经过测试用+号代替*号也是不可行的。

 

收集SQLite与Sql Server的语法差异


1.返回最后插入的标识值
返回最后插入的标识值sql server用@@IDENTITY
sqlite用标量函数LAST_INSERT_ROWID()
返回通过当前的 SQLConnection 插入到数据库的最后一行的行标识符(生成的主键)。此值与 SQLConnection.lastInsertRowID 属性返回的值相同。

2.top n
在sql server中返回前2行可以这样:
select top 2 * from aa
order by ids desc

sqlite中用LIMIT,语句如下:
select * from aa
order by ids desc
LIMIT 2

3.GETDATE ( )
在sql server中GETDATE ( )返回当前系统日期和时间
sqlite中没有

4.EXISTS语句
sql server中判断插入(不存在ids=5的就插入)
IF NOT EXISTS (select * from aa where ids=5)
BEGIN
insert into aa(nickname)
select 't'
END
在sqlite中可以这样
insert into aa(nickname)
select 't'
where not exists(select * from aa where ids=5)

5.嵌套事务
sqlite仅允许单个活动的事务

6.RIGHT 和 FULL OUTER JOIN
sqlite不支持 RIGHT OUTER JOIN 或 FULL OUTER JOIN

7.可更新的视图
sqlite视图是只读的。不能对视图执行 DELETE、INSERT 或 UPDATE 语句,sql server是可以对视图 DELETE、INSERT 或 UPDATE

 

posted @ 2009-10-24 12:09  彷徨......  阅读(2138)  评论(0编辑  收藏  举报