分类目录
文章索引模板
SQLite faq - 二月 4, 2010 by yippee

(1) 如何创建自增字段?



简单的回答:一个声明为 INTEGER PRIMARY KEY 的字段将自动增加。


这里是详细的答案: 从 SQLite 的 2.3.4 版本开始,如果你将一个表中的一个字段声明为 INTEGER PRIMARY KEY,那么无论你何时向该表的该字段插入一个 NULL 值,这个 NULL 值将自动被更换为比表中该字段所有行的最大值大 1 的整数;如果表为空,那么将被更换为 1。比如,假设你有这样的一张数据表:


CREATE TABLE t1(
a INTEGER PRIMARY KEY,
b INTEGER
);

在这张数据表里,声明


INSERT INTO t1 VALUES(NULL,123);

在逻辑意义上等价于:


INSERT INTO t1 VALUES((SELECT max(a) FROM t1)+1,123);

一个新的API函数 sqlite3_last_insert_rowid() 返回最近的插入操作的整形键


注意这个整型键始终比之前插入表中的最后一个键大1。新键相对于表中的已有键来说是唯一的, 但它可能与之前从表中删除的键值重叠。要始终得到在整个表中唯一的键,在INTEGER PRIMARY KEY的声明之前加关键词AUTOINCREMENT.这样被选的键将总是比表中已存在的最大键大1。若可能的 最大键已存在于表中,INSERT操作将失败并返回一个SQLITE_FULL错误码.



(2) SQLite 支持哪些数据类型?



参见 http://www.sqlite.org/datatype3.html.



(3) 为什么能向 SQLite 数据库的整型字段中插入字符串?



这是一个功能,不是一个 bug。你可以在任何字段中放任何信息,而不用管字段声明为什么类型。 你可以往整型字段中插入任意长度的字符串,或者往布尔字段中插入浮点数,或者往字符字段中 插入日期。在 CREATE TABLE 命令中你指定给这个字段的数据类型不会限制插入这个字段的数据。 所有的字段可以插入任意长度的字符串。但对于 INTEGER PRIMARY KEY 字段例外。这种字段只能 存放一个64位的整数,否则会出错。


但SQLite会默认你希望使用声明的字段类型。所以,比如你希望在一个声明为INTEGER的字段 中插入一个字符串,SQLite会试图将其转换为一个整数。如果转换成功,那么整数将被插入,否 则插入字符串,这种特性有时被称作type or column affinity.



(4) 为什么 SQLite 认为表达式 ‘0′==’00′ 为真?



在 2.7.0 之后,表达式不成立。参见文档 datatypes in SQLite version 3



(5) 为什么 SQLite 不允许在同一张表里使用 ‘0′ 和 ‘0.0′ 作为两个不同的行的主键?



你的主键一定是数值类型的,把类型改为 TEXT 就可以了。


每一行必须有一个唯一的主键。作为一个数字类型的字段,SQLite 认为 ‘0′‘0.0′的值是相同的, 因为他们在数字上的比较是相等的(看前面的问题)因此值不是唯一的。



(6) 为什么不能在 Linux box 中读取在 SparcStation 中创建的 SQLite 数据库?



你需要升级你的 SQLite 库到 2.6.3 或更新版本。


x86 处理器是 little-endian 型的而 Sparc 是 big-endian 型的。新版本的 SQLite 解决了这个问题。


注:   big endian和little endian是CPU处理多字节数的不同方式。例如“汉”字的Unicode编码是6C49。那么写到文件里时,究竟是将6C写在前面,还是将49写在前面?如果将6C写在前面,就是big endian。还是将49写在前面,就是little endian。



(7) 多个应用程序或者同一个应用程序的多个例程能同时存取同一个数据库文件吗?



多进程可以同时打开同一个数据库,也可以同时 SELECT 。但只有一个进程可以立即改数据库。


SQLite使用读/写锁定来控制数据库访问。(Win95/98/ME 操作系统缺乏读/写锁定支持,在低于 2.7.0 的版本中,这意味着在 windows 下在同一时间内只能有一个进程读数据库。在版本 2.7.0 中 这个问题通过在 windows 接口代码中执行一个用户间隔几率读写锁定策略解决了。) 但如果数据库文件在一个 NFS 文件系统中,控制并发读书的锁定机制可以会出错。因为 NFS 的fcntl() 文件锁定有时会出问题。如果有多进程可能并发读数据库则因当避免把数据库文件放在 NFS 文件系统中。 根据微软的文档,如果不运行 Share.exe 后台程序则 FAT 文件系统中的锁定可能不工作。对 Windows 非常有经验的人告诉我网络文件的锁定有许多问题并且不可靠。如果是这样,在2个或以上 Windows 系统中共享一个 SQLite 数据库文件会导致不可预知的问题。


我们知道没有其他的嵌入式 SQL数据库引擎比SQLite支持更多的并发性。 SQLite允许多进程 同时打开和读取数据库。任何一个进程需要写入时,整个数据库将在这一过程中被锁定。但这一般仅耗时 几毫秒。其他进程只需等待然后继续其他事务。其他嵌入式SQL数据库引擎往往只允许单进程访问数据库。


但是,client/server型的数据库引擎 (如 PostgreSQL, MySQL, 以及 Oracle) 通常支持更高的并发度, 并支持多进程同时写入同一个数据库。由于总有一个控制良好的服务器协调数据库的访问,这才保证了以上 特性的实现。如果你的应用需要很高的并发度,你应该考虑使用client/server数据库。事实上,经验告诉 我们大多数应用所需要的并发度比他们的设计者们想象的要少得多。


当 SQLite 尝试操作一个被另一个进程锁定的文件时,缺省的行为是返回 SQLITE_BUSY。你可以用 C代码更改这一行为。 使用 sqlite3_busy_handler()sqlite3_busy_timeout() API函数。


如果两个或更多进程同时打开同一个数据库,其中一个进程创建了新的表或索引,则其它进程可能不能立即看见新的表。其它进程可能需要关闭并重新连结数据库。



(8) SQLite是线程安全的吗?



有时候是的。为了线程安全,SQLite 必须在编译时把 THREADSAFE 预处理宏设为1。在缺省的发行的已编译版本中 Windows 版的是线程安全的,而 Linux 版的不是。如果要求线程安全,Linux 版的要重新编译。


“线程安全”是指二个或三个线程可以同时调用独立的不同的sqlite3_open() 返回的”sqlite3“结构。而不是在多线程中同时使用同一个 sqlite3 结构指针。


一个sqlite3结构只能在调用 sqlite3_open创建它的那个进程中使用。你不能在一个线程中打开一个数据库然后把指针传递给另一个线程使用。这是因为大多数多线程系统的限制(或 Bugs?)例如RedHat9上。在这些有问题的系统上,一个 线程创建的fcntl()锁不能由另一个线程删除或修改。由于SQLite依赖fcntl()锁来进行并发控制,当在线程间传递数据库连接时会出现严重的问题。


也许在Linux下有办法解决fcntl()锁的问题,但那十分复杂并且对于正确性的测试将是极度困难的。因此,SQLite目前不允许在线程间共享句柄。


在UNIX下,你不能通过一个 fork() 系统调用把一个打开的 SQLite 数据库放入子过程中,否则会出错。



(9) 如何列出一个 SQLite 数据库中的所有的表/索引?



sqlite3 命令行程序中你可以用命令 “.tables” 来显示所有的表或者用 “.schema“来显示所有的表结构和索引。但命令后不要跟 LIKE 语句,否则会限制表的显示。


在 C/C++ 程序中 (或使用 Tcl/Ruby/Perl/Python绑定的脚本中)你可以通过访问名为”SQLITE_MASTER的表来实现。每个 SQLite 数据库有一个 SQLITE_MASTER 表,表内有数据库的结构。SQLITE_MASTER表是这样的:


CREATE TABLE sqlite_master (
type TEXT,
name TEXT,
tbl_name TEXT,
rootpage INTEGER,
sql TEXT
);

对于表来说,type字段的值为‘table’name 字段是表的名称。使用以下语句可以等到所有表的列表:


SELECT name FROM sqlite_master
WHERE type=’table’
ORDER BY name;

对于索引来说, type = ‘index’, name 是索引的名称, tbl_name 是索引所属的表的名称。对于表和索引,sql 字段是创建表或索引的原始语句文本。对于自动创建的索引(一般是使用 PRIMARY KEY 或 UNIQUE 创建的),sql字段为 NULL.


SQLITE_MASTER表是只读的。你不能对该表使用 UPDATE, INSERT, 或 DELETE。该表自动由 CREATE TABLE, CREATE INDEX, DROP TABLE 和 DROP INDEX 命令更新。


临时表及其索引不在 SQLITE_MASTER 表中而在 SQLITE_TEMP_MASTER 中出现。SQLITE_TEMP_MASTER 与 SQLITE_MASTER 表一样工作,但只对于创建临时表的程序可见。要得到所在表包括临时表可以使用如下命令:


SELECT name FROM
(SELECT * FROM sqlite_master UNION ALL
SELECT * FROM sqlite_temp_master)
WHERE type=’table’
ORDER BY name


(10) SQLite数据库是否有已知的大小限制?



数据库大小被限制在 2TB(241 bytes). 这是理论限制。事实上,你应该把 SQLite数据库的大小限制在100GB以下,以免出现运行性能上的问题。如果你需要储存100GB或更多数据在一个数据库中, 考虑使用为此而设计的企业版数据库吧。


一个数据库的理论行数限制是 264-1,显然你会在达到行数限制之前先超过文件大小的限制。目前一行可以存放 230 bytes 数据。而基本的文件格式可以支持行大小到约 262 bytes.


可能还会有对于表、索引的数目或表和索引中的字段数的限制,但没人知道是多少。事实上,每当新数据库打开时,SQLite需要读取和 分析所有表和索引声明的初始SQL,所以,为了调用 sqlite3_open() 时获得最佳性能,最好减少声明的表的数目。同样的,即使 对于表中字段数没有限制,多于100个也显得太多了。 只有表开头的31个字段会得到优化。你可以在一个索引中放入任意多的字段但超过30字段的索引将不用于优化查询。


表,索引,视图,触发器和字段名称可以任意长,但SQL 函数名 (由 sqlite3_create_function() API创建的)不得超过255个字符。



(11) 在 SQLite 中 VARCHAR 的最大长度是多少?



SQLite不强制VARCHAR的长度。你可以声明一个VARCHAR(10),SQLite一样可以让你存放500个字符在里面。 并且它们会始终完整无缺——决不会被截断。



(12) SQLite 是否支持 BLOB 类型?



SQLite 3.0 版支持在任何字段存放 BLOB 数据,不管字段声明为什么类型。



(13) 如何从一个已存在的 SQLite 数据表中添加/删除字段?



SQLite有有限的ALTER TABLE支持,可以用于添加字段到表的末尾 或更改表名。如果你要对表的结构作更复杂的修改,你需要重新创建表。你可以在一个临时表中备份数据,撤销旧表,重建新表后再恢复数据。


例如,假设你有一个名为 “t1″ 的表,有名为 “a”, “b”, 和 “c” 三个字段,你要删除字段 “c” 。可按如下步骤操作:


BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b);
INSERT INTO t1 SELECT a,b FROM t1_backup;
DROP TABLE t1_backup;
COMMIT;


(14) 我删除了很多数据但是数据库文件并没有减小,是不是 Bug?



不是的。当你从 SQLite 删除数据之后,未使用的磁盘空间被添加到一个内在的“空闲列表”中用于存储你下次插入的数据。磁盘空间并没有丢失,但是也不向操作系统返回磁盘空间。


如果你删除了大量的数据且想要减小数据库文件,执行 VACUUM命令。VACUUM 命令会清空“空闲列表”,把数据库尺寸缩到最小。注意, VACUUM 会耗费一些时间(在 Linux 系统下大约0.5秒/兆)并且要使用两倍于数据库文件大小的磁盘空间。


对于SQLite version 3.1, 替代VACUUM命令的一个方法是auto-vacuum模式,用 auto_vacuum pragma语法开启该模式。



(15) 是否能将 SQLite 用于商业用途而不用交版权费用?



可以。SQLite 是公开的。代码的任何部分都没有声明所有权。你可以用它来做你想要的任何事情。



(16) 如何插入有单引号(’)的字符串?



使用双单引号即可,例如:


    INSERT INTO xyz VALUES(‘5 O”clock’);


插入数据库的是:5 0′clock。



(17) SQLITE_SCHEMA 错误代表什么?



在 SQLite 版本3中,当一个预处理 SQL 语句不合法不能执行时就会返回一个 SQLITE_SCHEMA 错误。当这个错误发生时,该语句应当用 sqlite3_prepare() API函数重新编译。在 SQLite 版本3中,只有使用 sqlite3_prepare()/sqlite3_step()/sqlite3_finalize() API函数执行 SQL 才会发生这个错误,而使用 sqlite3_exec(). 则不会。这与版本2不同。


大部分发生这个错误的原因是当 SQL 预处理完时数据库已经改变了(可能是被另一个进程改变的)。还可能有如下原因:



  • 对一个数据库进行DETACH操作

  • 对一个数据库进行VACUUM操作

  • 一个用户函数定义被删除或改变了。

  • 一个排序定义被删除或改变了。

  • 一个授权函数改变了。

解决的办法是重新编译并再次尝试执行。所有涉及 sqlite3_prepare()/sqlite3_step()/sqlite3_finalize() API 函数的都应当重新编译。参见下例:


    int rc;
sqlite3_stmt *pStmt;
char zSql[] = “SELECT …..”;

do {
/* Compile the statement from SQL. Assume success. */
sqlite3_prepare(pDb, zSql, -1, &pStmt, 0);

while( SQLITE_ROW==sqlite3_step(pStmt) ){
/* Do something with the row of available data */
}

/* Finalize the statement. If an SQLITE_SCHEMA error has
** occured, then the above call to sqlite3_step() will have
** returned SQLITE_ERROR. sqlite3_finalize() will return
** SQLITE_SCHEMA. In this case the loop will execute again.
*/
rc = sqlite3_finalize(pStmt);
} while( rc==SQLITE_SCHEMA );



(18) 为什么ROUND(9.95,1) 返回 9.9 而不是 10.0? 难道9.95 不该向上进位么?



SQLite 内部使用二进制运算,9.95用 64-bit IEEE 浮点数 ( SQLite 内部使用的) 表示为9.949999999999999289457264239899814128875732421875。所以当你输入 “9.95″时,SQLite 就理解为上述的数字,进而四舍五入得到9.9。这个问题在处理浮点二进制数总会产生。通常的规则是十进制的有限浮点数通常无法表示为二进制有限浮点数,只能由最接近的二进制数来代替。这个近似数会非常接近原数,但总一些细微的不同,所以可能无法得到你预期的结果。

标签:
SQLite内建函数表 - 二月 3, 2010 by yippee

SQLite内建函数表






 

算术函数 
abs(X) 返回给定数字表达式的绝对值。
max(X,Y[,...]) 返回表达式的最大值。
min(X,Y[,...]) 返回表达式的最小值。
random(*) 返回随机数。
round(X[,Y]) 返回数字表达式并四舍五入为指定的长度或精度。
字符处理函数 
length(X) 返回给定字符串表达式的字符个数。
lower(X) 将大写字符数据转换为小写字符数据后返回字符表达式。
upper(X) 返回将小写字符数据转换为大写的字符表达式。
substr(X,Y,Z) 返回表达式的一部分。
randstr()  
quote(A)  
like(A,B) 确定给定的字符串是否与指定的模式匹配。
glob(A,B)  
条件判断函数 
coalesce(X,Y[,...])  
ifnull(X,Y)  
nullif(X,Y)  
集合函数 
avg(X) 返回组中值的平均值。
count(X) 返回组中项目的数量。
max(X) 返回组中值的最大值。
min(X) 返回组中值的最小值。
sum(X) 返回表达式中所有值的和。
其他函数 
typeof(X) 返回数据的类型。
last_insert_rowid() 返回最后插入的数据的ID。
sqlite_version(*) 返回SQLite的版本。
change_count() 返回受上一语句影响的行数。
last_statement_change_count()  

标签:
SQLite SubSonic - 一月 4, 2010 by yippee

SubSonic: All Your Database Are Belong To Us
http://subsonicproject.com/download



SubSonic介绍和相关文章 – 成功的心 Blog – CSDN博客
http://blog.csdn.net/baogreat/archive/2008/10/29/3176079.aspx
SubSonic


Subsonic 配置、安装、使用(1)_派行天下的空间
http://hi.baidu.com/ansonlau/blog/item/16dfdf5063f1d92d42a75bc7.html



Subsonic学习 – EricGu’s Record-Space – 博客园
http://www.cnblogs.com/EricGu/archive/2008/03/31/1131467.html



subsonic 如何使用 动态连接字符串?
http://topic.csdn.net/u/20080707/11/c5b51d13-b93d-4304-adfa-1fb48f717a79.html



使用SubSonic生成数据访问层步骤 – 王智勇的博客 – MySpace聚友免费博客
http://blog.myspace.cn/e/404745181.htm
<SubSonicService defaultProvider=”Nowthwin”>


    <providers>


      <clear/>


      <add name=”Nowthwin”


           type=”SubSonic.SqlDataProvider, SubSonic”


           connectionStringName=”Nowthwin”


           generatedNamespace=”Nowthwin”/>


    </providers>


  </SubSonicService>


ExtAspNet应用技巧(十一) – Subsonic配置与使用 – sanshi – 博客园
http://www.cnblogs.com/sanshi/archive/2009/08/25/1553917.html#viewSource



subsonic sqlite connectstring – Google Search
http://www.google.com/search?q=subsonic+sqlite+connectstring&btnG=Search&hl=en&client=firefox&rls=org.mozilla%3Azh-CN%3Aofficial&newwindow=1&ie=UTF-8&oe=UTF-8&sa=2



Simple Query Tool – SubSonic :: Tome
http://subsonicproject.com/docs/Simple_Query_Tool



ActiveRecord – SubSonic :: Tome
http://subsonicproject.com/docs/ActiveRecord



SQLite Data Provider for Subsonic. Part 2. « CodeForNothing
http://codefornothing.wordpress.com/2007/07/19/sqlite-data-provider-for-subsonic-part-2/



Using SQLite as a Data Store in Dot Net « Bag of Spanners
http://bagofspanners.wordpress.com/2009/09/17/using-sqlite-as-a-data-store-in-dot-net/



SQLite Data Provider for Subsonic. Part 3. « CodeForNothing
http://codefornothing.wordpress.com/2007/07/21/sqlite-data-provider-for-subsonic-part-3/



The SQLite Data Provider is now part of SubSonic « CodeForNothing
http://codefornothing.wordpress.com/2007/07/24/the-sqlite-data-provider-is-now-part-of-subsonic/



SQLite Data Provider for Subsonic. Part 2. « CodeForNothing
http://codefornothing.wordpress.com/2007/07/19/sqlite-data-provider-for-subsonic-part-2/



InfoQ: Up and Running with SQLite on .NET in 3 Minutes
http://www.infoq.com/news/2008/01/sqlite-in-three-minutes



SubSonic: All Your Database Are Belong To Us
http://forums.subsonicproject.com/t/3417.aspx



SubSonic connection string for SQLite – Stack Overflow
http://stackoverflow.com/questions/808175/subsonic-connection-string-for-sqlite



SQLite Data Provider for Subsonic. Part 1. « CodeForNothing
http://codefornothing.wordpress.com/2007/07/15/sqlite-data-provider-for-subsonic-part-1/



The SQLite Data Provider is now part of SubSonic « CodeForNothing
http://codefornothing.wordpress.com/2007/07/24/the-sqlite-data-provider-is-now-part-of-subsonic/



SubSonic, SQLite and Unable to find Data Provider? – Stack Overflow
http://stackoverflow.com/questions/1950523/subsonic-sqlite-and-unable-to-find-data-provider



SubSonic connection string for SQLite – Stack Overflow
http://stackoverflow.com/questions/808175/subsonic-connection-string-for-sqlite
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @”MyApplication\Northwind.db3″);


DataService.Providers["Northwind"].DefaultConnectionString =
            String.Format(@”Data Source={0};Version=3;New=False;Connection Timeout=3″, dbPath);


SubSonic connection string for SQLite – Stack Overflow
http://stackoverflow.com/questions/808175/subsonic-connection-string-for-sqlite



New SQLiteDataProvider for SubSonic using System.Data.SQLite – System.Data.SQLite
http://sqlite.phxsoftware.com/forums/t/823.aspx



SQLite on .NET in 3 minutes. Download to querying in no time flat. | MikeDuncan.com C# Dev tips, patterns and tools you can actually use.
http://www.mikeduncan.com/sqlite-on-dotnet-in-3-mins/



 

标签:,
20090710 php sqlite wordpress - 八月 18, 2009 by yippee

今天开始折腾WP了


要在PHP5里面开启SQLITE支持


extension=php_pdo.dll
extension=php_pdo_sqlite.dll
extension=php_sqlite.dll


否则会报告:


Fatal error: Call to undefined function sqlite_open() in xxx.php on line XX


<?php
print_r(PDO::getAvailableDrivers());


      $db=sqlite_open(“db.sqlite”); //打开db.sqlite数据库,如果不存在则尝试创建。
 sqlite_query($db,”drop table test”);
 sqlite_query($db,”create table test (id INTEGER PRIMARY KEY,name text);”); //创建test表,id字段为自动递增主键
 sqlite_query($db,”insert into test (name) values(‘hello’);”); //插入一行内容
 sqlite_query($db,”insert into test (name) values(‘world’);”);//插入一行内容
 $result=sqlite_query($db,”select * from test”); //取得test表的所有内容
 while($row=sqlite_fetch_array($result)) { //通过while循环表中所有内容
   print “”;
   print_r($row); 
   print “”;
 }
 sqlite_close($db);//关闭数据库的连接


?>


输出:
Array ( [0] => mysql [1] => sqlite [2] => sqlite2 ) Array ( [0] => 1 [id] => 1 [1] => hello [name] => hello ) Array ( [0] => 2 [id] => 2 [1] => world [name] => world ) ?>


验证完后,按照 http://wordpress.org/extend/plugins/pdo-for-wordpress/installation/



  • Step 1: unzip the files in your wp-content directory. After unzipping the structure should look like this


    wp-content
    ->plugins
    ->themes
    ->pdo
    db.php
    index.php[maybe]


    The key thing is the presence of the pdo directory and the db.php file in the ‘root’ of the wp-content directory.



  • Step 2: Edit your wp-config.php file so that:


    this line of code is placed directly after the define(‘COLLATE’,”); line:

    define(‘DB_TYPE’, ’sqlite’);    //mysql or sqlite`

    Note: currently only mysql and sqlite are supported. I hope that more flavours will appear soon.


  •  

    标签:, , , ,
    20090709 wordpress sqlite url database - 八月 18, 2009 by yippee

    既然初步决定使用WP,就收集了一些相关的资料


    关于SQLITE:


    系统环境依赖要求:
    主机php套件必须支持SQLite和PDO扩展(不过放心,常见系统都是完美支持的);SQLite的数据库信息存于独立文件中,该文件及文件夹必须要求读写权限。很简单,就这些要求。


    升级更换wordpress数据系统:
    这里指出一个简易的方法:首先在wordpress后台中使用“工具-导出”功能导出.xml文件。


    然后,下载SQLite的wordpress功能插件-“PDO(SQLite) For Wordpress”,将压缩包中的db.php和pdo文件夹放置到wp-content文件夹中。


     


    然后,编辑wp-config.php文件,在define(‘DB_COLLATE’, ”); 后面加入“define(‘DB_TYPE’,’sqlite’);”。


    关于URL重写


    进入管理后台,点菜单紧靠右边的“设置”,点选其下的“永久链接”(Permalinks)
    点选“自定义,请在下面填入自定义结构”,再其下框里输入:/posts/%post_id%.html
    点页面右下按钮“更新永久链接结构>>”保存设置,此时在 Wordpress 的根目录自动生成里一 .htaccess 文件,内容大体如下:
    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /codemo/wordpress23/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /codemo/wordpress23/index.php [L]
    </IfModule>
    # END WordPress
    刷新下你的 Wordpress 首页,便会发现帖子链接都变成形如:http://www.yyyqi.com/codemo/wordpress23/posts/1.html 的静态页形式了,伪静态顺利实现!
    另,其它自定义永久链接写法及对应效果:
    0、
    Permalinks写法:/%year%/%monthnum%/%postname%/
    效果:http://www.yyyqi.com/2007/03/zero-to-riding-the-rails-in-four-months.html
    1、
    Permalinks写法:/%year%/%monthnum%/%day%/%postname%/
    效果:http://www.yyyqi.com/2007/10/14/zero-to-riding-the-rails-in-four-months/
    2、
    Permalinks写法:/%year%/%monthnum%/%postname%.html
    效果:http://www.yyyqi.com/2007/03/zero-to-riding-the-rails-in-four-months.html
    3、
    Permalinks写法:/%year%/%monthnum%/%day%/%postname%.html
    效果:http://www.yyyqi.com/2007/03/15/zero-to-riding-the-rails-in-four-months.html
    4、
    Permalinks写法:/%category%/%postname%.html
    效果:http://www.yyyqi.com/category/zero-to-riding-the-rails-in-four-months.html


    关于数据导入导出···
    wordpress数据库表基本结构:


    wp_options:系统基本设置信息;
    wp_users:注册用户基本信息;
    wp_usermeta:注册用户附加信息,主要包括权限等设置;
    wp_categories: 日记分类,友站链接(blogroll)也包含其中;分类之间也可以有从属关系;公开日记在category_count中计数,私人日记不计数;
    wp_links:友站链接(blogroll);
    wp_link2cat: 友站链接的分类;
    wp_posts:日记,其中的上传的附件和图片也作为其中的记录,不过类别不同,与日记存在从属关系;其中有几个字段好像没用,如: post_category,post_parent
    wp_post2cat:日记(包括附件)的分类;
    wp_postmeta:日记中的一些附加信息,也包括上传附件的一些附加信息,自定义字段也存在这里,如:Jerome’s Keywords的tag属性就是保存在这里的;
    wp_comments:评论,评论的游客的userid为0;


    wordpress仅仅用了 10 个 Table就实现了这么强大的系统,让我钦佩:


        wp_comments
        wp_links
        wp_options
        wp_postmeta
        wp_posts
        wp_term_relationships
        wp_term_taxonomy
        wp_terms
        wp_usermeta
        wp_users


    下面我们按照它们之间的关系来介绍一下这几个表:


    按照功能大致分为五类。


        * user: 用户信息,包括wp_users表和wp_usermeta表。
        * link:链接信息,包括wp_links表。
        * post: 文章及评论信息,包括wp_posts、wp_postmeta、wp_comments。
        * category,link_category,tag:这个是比较复杂的信息模块,它包含了对分类,链接分类,标签的管理,包括wp_term,wp_term_relationships和wp_term_taxonomy表。
        * option: 全局设置信息,包括wp_options表。


    wp_posts
    作为一个博客系统,最核心的当然是博主发表的一些“文章”了,这些“文章”存放的地方就是这个 wp_posts 表了。注意,这里所说的“文章”是加引号的,因为这个表里存放的除了普通的文章之外,还有附件和页面(page)的一些信息。表里面的 post_type 这个字段就是用来标示类型的。还有一点需要注意的就是,这个表里一些字段是针对于 post_type 的特定类型的,比如 menu_order 这个字段是“页面(page)”特有的,用来指定“页面”的顺序。post_mime_type 是针对附件的,来指定附件的类型。


    wp_postmeta
    每篇文章的属性是不可能仅仅用 wp_posts 表里的那几个字段来完全标示的,往往还有一些因人而异的属性:写这篇文章时候的心情,地点等等。这些属性的名称和值类型都是不确定的,因此,Wordpress 采用了元信息(meta)来表示它们。这个表很简单,只有 meta_id, post_id, meta_key, meta_value 这四个字段。post_id 是相关 post 的 id。我们注意到 meta_value 是 longtext 类型的,这里仅是用来存储值,至于值的确切类型,需要程序员来关心。
    在撰写文章的时候,我们可以发现编辑框下面有一个 Custom Fields 的选项,我们可以在这里添加 post 的 meta 信息。


    wp_comments
    用户评论。除了评论的内容以外,还记录了评论用户的名字,邮箱,网址,浏览器类型等信息。比较重要的两个字段是 comment_post_ID 和 comment_approved,前一个用来指示这条评论隶属于哪一篇文章,后一个用来记录审核状况。还有一个比较有意思的是这个 commnet_agent 字段,我们可以利用这个字段来统计一下用户浏览器类型。


    wp_users
    用户帐号表。存储用户名、密码还有一些用户的基本信息。


    wp_usermeta
    类似上面的 wp_postmeta,存储一些因人而异的用户信息。(比如QQ?ICQ?)


    wp_options
    用来记录 Wordpress 的一些设置和选项。里面有一个 blog_id 字段,这个应该是用在 MU 版里面来标示不同的 Blog 的。


    wp_links
    用来存储 Blogroll 里面的链接。


    wp_terms
    wp_term_relationships
    wp_term_taxonomy


    这三个表是这里面关系最复杂的了,在 Wordpress 2.2 及以前的版本中是没有这三个表的,代之的是 wp_categories、wp_post2cat 和 wp_link2cat 这三个表。对比这两个版本我们可以发现:在 2.2 版和之前的版本,post 和 link 和 category 的关系都是通过各自单独的表来记录的。而在 2.3 版中加入了 tag 的支持,Wordpress 把 post、link、tag 的分类都抽象成了统一的形式,用新的三个表来记录这些信息。
    wp_terms
    记录分类,链接分类,标签的一些简要信息,包括名称,缩写。


    wp_term_taxonomy
    是对wp_terms中的信息的关系信息补充,有所属类型(category,link_category,tag),详细描述,父类,所拥有文章(链接)数量。


    wp_term_relationships
    关系表,多对多的,object_id是与不同的对象关联,例如wp_posts中的ID(wp_links中的link_id)等,term_taxonomy_id就是关联wp_term_taxonomy中的term_taxonomy_id。

    标签:, , , ,
    20090624 sqlite insert or ignore - 八月 18, 2009 by yippee

     public override int Insert( HelpEntity e ) &leftsign;
                //构造sql
                string sql = "INSERT INTO [HelpEntity](Name,Nickname,Text,IsIncluded,Guid)VALUES(@Name,@Nickname,@Text,@IsIncluded,@Guid);select last_insert_rowid()";

                //参数构造
                SQLiteParameter[] parameters = &leftsign;
                    new SQLiteParameter("@Name",DbType.String),
                    new SQLiteParameter("@Nickname",DbType.String),
                    new SQLiteParameter("@Text",DbType.String),
                    new SQLiteParameter("@IsIncluded",DbType.Boolean),
                    new SQLiteParameter("@Guid",DbType.Guid),
                &rightsign;;

                //为参数赋值
                int i = 0;
                parameters[ i++ ].Value = e.Name;
                parameters[ i++ ].Value = e.Nickname;
                parameters[ i++ ].Value = e.Text;
                parameters[ i++ ].Value = e.IsIncluded;
                parameters[ i++ ].Value = e.Guid;

                //执行查询
                try &leftsign;
                    object obj = db.ExecuteScalar( CommandType.Text, sql, parameters );
                    if( obj != null )
                        return int.Parse( obj.ToString() );
                    return -1;
                &rightsign; catch( Exception exp ) &leftsign;
                    throw exp;
                &rightsign;
            &rightsign;

    ~
    Look at the sqlite.org: http://www.sqlite.org/lang_expr.html

    last_insert_rowid() Return the ROWID of the last row insert from this connection to the database.

    It returns last inserted rowid inside connection! You always do open and close connection while querying database. Iif you query \’last_insert_rowid()\’ you do tha same: open new connection and then you get 0.

    I know all that, but i have the same problem. I\’m using microsoft visual studio express C# with tableadapters. All queries are like: this.tableadapter.query(parameters).
    ~
    Change your SQL to:

    "insert into people (Name) values(@Name);
     SELECT last_insert_rowid() AS RecordID;";

    Then call ExecuteScalar() on it instead of ExecuteNonQuery() to get the rowid.

    Also your table definition should be:

    CREATE TABLE People (RecordID INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR);

    Robert
    ~
    ExecuteScalar方法返回的类型是object类型,这个方法返回sql语句执行后的第一行第一列的值,由于不知到sql语句到底是什么样的结构(有可能是int,有可能是char等等),所以ExecuteScalar方法返回一个最基本的类型object,这个类型是所有类型的基类,换句话说:可以转换为任意类型。

    ExecuteNonQuery方法是用来执行insert、delete、update语句的,由于这些语句执行后只有一个结果:“影响了**行”,所以ExecuteNonQuery方法返回的是影响的行数(int)。

    虽然SQL中列的name本身就是字符串类型,但是你通过dataReader["name"]这种方式访问这个字段,必须强制类型转换,因为dataReader["name"]就像一个数组,数组中的每个元素的类型都应该一样,所以dataReader[]这个数组中的元素类型也被定义为object类型,以方便转换。

    int.Parse(("select max(id) from [tb]").ToString())+1);

    select top 1 id from [tb] order by id desc

    select SCOPE_IDENTITY()

    I need something like: http://sqlite.phxsoftware.com/forums/p/1029/4441.aspx#4441

    INSERT INTO Timeline (name, ts)
    SELECT @name, @ts
    WHERE NOT EXISTS (SELECT 1 FROM Timeline WHERE name=@name AND ts = @ts);

    It works fine with insert. I was wondering if update can be added to the above statement.

    ~
    C:\\sqlite>sqlite3.exe testdb.db
    SQLite version 3.5.1
    Enter ".help" for instructions
    sqlite> create table people (lastname text, firstname text, salary double);
    sqlite> create unique index people_unique_1 on people (lastname, firstname);
    sqlite> insert or ignore into people values (\’smith\’, \’john\’, 44548.33);
    sqlite> select * from people;
    smith&line;john&line;44548.33
    sqlite> insert or ignore into people values (\’smith\’, \’john\’, 44548.33);
    sqlite> select * from people;
    smith&line;john&line;44548.33
    sqlite> insert or ignore into people values (\’smith\’, \’linda\’, 44548.33);
    sqlite> select * from people;
    smith&line;john&line;44548.33
    smith&line;linda&line;44548.33
    sqlite>

    标签:,
    20090625 sqlite htnl editor - 八月 18, 2009 by yippee

    HTML viewing and editing component for WinForms apps
    Heres some sample code that allows you to incorporate HTML viewing and editing into your own Windows Forms app.
    http://www.nikhilk.net/HTMLEdITingComponent.ASPx
    功能毕竟简单,代码却是不少

    A Windows Forms based text editor with HTML output
    By kevin delafield

    A Windows Forms based text editor with HTML output, implemented with a browser control in edit mode.
    http://www.codeproject.com/KB/edit/editor_in_windows_forms.aspx
    这个不错

    An extended RichTextBox to save and load "HTML lite" files
    By Oscar Londono

    This control provides a method to save and load HTML files directly, avoiding the use of RTF codes.
    似乎对汉字不是特别兼容

    WinForms C#:html编辑器工程源码,含直接写WebBrowser的文件流、IPersistStreamInit接口的声明和一些相关的小方法
    这个好像不是很··

    HTML viewing and edITing component for WinForms apps

    http://www.nikhilk.NET/HTMLEdITingComponent.ASPx

    http://www.codeproject.com/cs/miscctrl/edITor_in_windows_forms.ASP
    http://www.codeproject.com/cs/miscctrl/HTMLrichtextbox.ASP

     ~
     Sqlite数据库里指定数据类型为:Blob。

    在数据访问指定参数类型为:DbType.Binary

    然后把Excel文件读到字节数组里。

            using(FileStream file = File.Open(this.TextBox2.Text,FileMode.Open))
            &leftsign;       
                byte[] bytes = new byte[file.Length];
                file.Read(bytes, 0, Convert.ToInt32(file.Length));
                testDal.Insert(Guid.NewGuid().ToString(), bytes, null);
            &rightsign;

    数据访问存储字节数据。
    public Int32 Insert(string ID,Byte[] fileStream, SQLiteTransaction trans)
            &leftsign;
                if (conn.State == ConnectionState.Closed)
                &leftsign;
                    conn.Open();
                &rightsign;
                SQLiteCommand command;
                if (trans == null)
                &leftsign;
                    command = new SQLiteCommand("insert into test(ID,excelText) values (:ID,:excelText)", conn);
                &rightsign;
                else
                &leftsign;
                    command = new SQLiteCommand("insert into test(ID,excelText) values (:ID,:excelText)", conn, trans);
                &rightsign;
                command.Parameters.Add("ID", DbType.String);
                command.Parameters.Add("excelText", DbType.Binary);

                command.Parameters["ID"].Value = ID;
                command.Parameters["excelText"].Value = fileStream;
                try
                &leftsign;
                    return command.ExecuteNonQuery();
                &rightsign;
                catch
                &leftsign;
                    return 0;
                &rightsign;
            &rightsign;

    根据主键返回Excel的字节数据
            public byte[] GetExcel(string ID)
            &leftsign;
                if (conn.State == ConnectionState.Closed)
                &leftsign;
                    conn.Open();
                &rightsign;
                SQLiteCommand command = new SQLiteCommand("Select excelText from test where ID = :ID", conn);
                command.Parameters.Add("ID", DbType.String);
                command.Parameters["ID"].Value = ID;

                SQLiteDataReader dr = null;

                dr = command.ExecuteReader();

                byte[] File = null;
                if (dr.Read())
                &leftsign;
                    File = (byte[])dr[0];
                &rightsign;
                return File;
            &rightsign;

    把字节数据存储为文件
            using (FileStream fs = File.Create("D:\\\\Test.xls"))
            &leftsign;
                fs.Write(file, 0, file.Length);
                fs.Close();
            &rightsign;
     ~
       A。
      该方法主要是利用了 SQLiteParameter 的功能,读取blob字段。代码如下:

        FileStream m_filestream = null;
      
                try &leftsign;
               
                    m_filestream = new FileStream(@"d:\\pcinfo\\17.jpg", FileMode.Open, FileAccess.Read);          //读取图片

                    SQLiteCommand m_commd2=new SQLiteCommand();
                    m_commd2.CommandText="UPDATE test1 set timage=@idimage WHERE tparendid=78";
                                
                   
                    Byte[] m_byte = new Byte[m_filestream.Length]; //存放图片

                    m_filestream.Read(m_byte,0,m_byte.Length);

                    m_filestream.Close();

                    SQLiteParameter param_m=new SQLiteParameter("@idimage",DbType.Binary,m_byte.Length,                    ParameterDirection.Input,false,0,0,null,DataRowVersion.Current,m_byte);
                    m_commd2.Parameters.Add(param_m);                m_commd2.Parameters.Add(param_m);      //很多参数阿,注意DBType.Binary
      
                    m_commd2.Connection = m_conn;
                    m_commd2.ExecuteNonQuery();

              &rightsign;
                catch (SQLiteException ex)
                &leftsign;

                    MessageBox.Show("未能存入图片");
      
                &rightsign;
         ~
         在C#中,在datagridview列表中可能会出现日期格式不对的错误。

    发现若在SQLite中的日期格式字段如果写成 2008-8-21 在填充到datagridview中就会报错,说日期格式不对。但如果把2008-8-21 改成 2008-08-21 就OK了,晕,2008-8-21 和2008-08-21 有区别么。。。

    没办法,只能在编辑页面的DateTimePicker 控件上做出改变

    DateTimePicker tmpDtp = new DateTimePicker();
    tmpDtp.CustomFormat = "yyyy-MM-dd";
    tmpDtp.Format = DateTimePickerFormat.Custom;

    标签:, ,
    20090718 wordpress OK - 八月 18, 2009 by yippee

    搞了半天,终于搞定了。

    由于空间PHP版本的问题,没有办法使用SQLITE

    本机很快就已经搭建完成。

    数据也很快导入了。

    但是发布出现两个问题

    1、当部署到服务器的时候,安装插件的时候,发现TAG不正常显示,直接搜索插件也提示出现未知错误。原本是把自己本机弄好的直接上传,因此重新弄了一次。重新进行干净安装。但是奇怪的是,问题还是存在,然后在网吧又是正常的。

     由于服务器速度问题,数据导入倒出问题,导致折腾了好几天。

    2、数据错位问题,也许由于垃圾留言的影响,导致丢了几个BLOG,结果导入的时候没有发现,直接忽略空白内容,导致错位,标题和内容失配,只好又重新来过,这次在网吧折腾,好像速度会快些。

    主题采用的是:Contrast Style 1.1 三栏,因为比较喜欢堆彻东西。

    插件用了不少

    Antispam Bee 屏蔽垃圾留言的

    Akismet 自带反垃圾留言的,但是不知道到哪里去找被它砍掉的留言(上线才半天,报告干掉了24个)

    Disable Canonical URL Redirection WP默认首页为不带index.php

    Genki Announcement 公告栏

    Peter’s Custom Anti-Spam 增加留言验证码

    Simple Tags 智能标签,这个比较强大

    Some Chinese Please 屏蔽纯洋文留言,上次就被阿拉伯文搞死两个BLOG

    Wordpress Thread Comment 嵌套留言

    WP-PageNavi 页码导航 但是不能输入

    WP-PostViews BLOG点击数

    WP-T-Wap WAP插件

    WP Kit CN 强大 

    用来解决官方 WordPress 没有照顾到的中文相关问题。使用这个插件,你可以显示随机文章,最新留言(最新引用),留言最多文章,发表评论最多的网友,还有真正的文章摘要,等等,真正截断,没有乱码。此插件在桑葚基础上修改,支持最新评论显示表情。支持指定最新评论截断字数。使用了对中文兼容更好的截断算法,现在控制字数更精确了。

    Genki AnnouncementSCP SettingPageNaviPostViewsWP-T-WAPSimple TagsWP Kit CN

    标签:, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
    20080911 c# sqlite - 五月 9, 2009 by yippee

    20080911 c# sqlite
    http://www.yippeesoft.com

    db4o Developer Community
    http://developer.db4o.com/

    [转]如何高效使用SQLite .net (C#) – Hyke Wants to Learn asp.net (C#) – 博客园
    http://www.cnblogs.com/yelsea/archive/2007/06/21/792314.html

    C#访问SQLite数据库,.net实例,.net技巧,.net教程,电脑教程,软件教程,学网
    http://www.xue5.com/itedu/200802/106684.html
    下载System.Data.SQLite(http://sqlite.phxsoftware.com/),安装

    3.打开VS2005,参考System.Data.SQLite安装目录下的System.Data.SQLite.DLL

                SQLiteConnection cnn = new SQLiteConnection();
                cnn.ConnectionString = @"Data Source=c:sqlite-3_5_0mytest.db";
                cnn.Open();

                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = cnn;
                cmd.CommandText = "SELECT * FROM mytable1";
                SQLiteDataAdapter da = new SQLiteDataAdapter();
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();
                da.Fill(ds);

    CodeProject: Using SQLite in your C# Application. Free source code and programming help
    http://www.codeproject.com/KB/cs/SQLiteCSharp.aspx

    CodeProject: Simple C# Wrapper for SQLite. Free source code and programming help
    http://www.codeproject.com/KB/database/cs_sqlitewrapper.aspx

    CodeProject: SQLite GUI. Free source code and programming help
    http://www.codeproject.com/KB/database/SQLite_GUI.aspx

    Using SQlite in c#
    http://www.developersdex.com/csharp/message.asp?p=1111&r=6064845
    http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers has some linkes
    to .NET wrappers.

    Finisar.SQLite
    http://adodotnetsqlite.sourceforge.net/documentation/csharp_example.php

    SourceForge.net: Files
    http://sourceforge.net/project/showfiles.php?group_id=132486&package_id=145568
    You have selected SQLite for ADO.NET 2.0
    Please choose the file that best matches your architecture or operating system from the list of releases and files contained in this package.

    Create SQLite DB and SQLite table using C# in Visual Studio 2005 – System.Data.SQLite
    http://sqlite.phxsoftware.com/forums/p/1042/4512.aspx
    using (cn = new SQLiteConnection(connectionString)) &leftsign;

        using (cmd = cn.CreateCommand()) &leftsign;

            cmd.CommandText = "create table tablename (column1 int, column2 char(1), etc);";

            cmd.CommandType = CommandType.Text;

            cn.Open();

            cmd.Execute();

            cn.Close();

        &rightsign;

    &rightsign;

    System.Data.SQLite
    http://sqlite.phxsoftware.com/
    1.0.58.0 Aug 30, 2008
    SQLite : 3.6.2

    SourceForge.net: Files
    http://sourceforge.net/project/showfiles.php?group_id=132486&package_id=145568&release_id=623152

    SQLite CVSTrac
    http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers
    ADO.NET 2.0/3.5 Provider for SQLite Supports Full and Compact Framework, Mono, ADO.NET Entity Framework, Visual Studio 2005/2008 Design-Time Support.

    SourceForge.net: ADO.NET 2.0 Provider for SQLite
    http://sourceforge.net/projects/sqlite-dotnet2
    ADO.NET 2.0/3.5 Provider for SQLite. Supports Full and Compact Framework, Entity Framework, complete with full Visual Studio 2005/2008 design-time support.

    SourceForge.net: Files
    http://sourceforge.net/project/showfiles.php?group_id=94056
    ADO.NET Data Provider for SQLite (This project is deceased, please refer to http://sourceforge.net/projects/sqlite-dotnet2)

    SQLite ADO.NET 驱动(C#) – Sqlite China
    http://www.sqlitechina.org/html/1/20071221/148.html

    和C#相关的嵌入式数据库_.Net技术文章_Asp.net_网站开发
    http://www.diybl.com/course/4_webprogram/asp.net/netjs/200847/108725.html
    #

    Native to .NET 2 incl. Compact Framework

    #

    100% object-oriented, no object-relational mapping

    #

    Designed for embedded use in zero-admin environments

    db4o 开源对象数据库
    http://www.db4o.com/china/Default.aspx?AspxAutoDetectCookieSupport=1

    标签:, ,
    20071015 sqlite cpp - 七月 6, 2008 by yippee

    20071015 sqlite cpp
    http://www.yippeesoft.com

    按 官方网站上的说法(国内也有相应的站点),它的特点是:易于管理,易于使用,易于嵌入其他大型程序,易于维护和配置 作为数据库引擎SQLite适用于中小规模流量的网站(也就是说, 99.9%的网站). SQLite可以处理多少网站流量在于网站的数据库有多大的压力. 通常来说, 如果一个网站的点击率少于100000次/天的话, SQLite是可以正常运行的. 100000次/天是一个保守的估计, 不是一个准确的上限. 事实证明, 即使是10倍的上述流量的情况下SQLite依然可以正常运行. 感觉上做网站用Sqlite是再好不过的了。轻量级,很好移植。到官方主页下载源码,用gcc编译。然后就可以调用了。使用下来感觉到几个比较好的地方:1) sql语句支持类似ADO.NET中command这样的东东,可以支持?这样的通配符,通配符变量,在后面赋值,这样C语言就不必做字符串的链接了,好处不言而喻,因为C语言处理字符很麻烦,要防止溢出,分配内存什么的。这里我就不举例子了,后面会把我用C写的CGI程序代码公开。2)分页非常方便, web程序分页经常用到,分页是个大问题。sqlite支持这样的语法select * from table limit a offset b ,这里limit后面就是要返回的记录数目,offset是偏置,就是从那里开始查询,是不是非常好,即简单,有高效,每次查询只查需要的记录,而不会查询所有的记录。3)就是非常好移植,C语言调用静态库的话,无需任何依赖,目标代码在web服务器上就可以运行了。 说了这么多sqlite的好处,总结一下C语言写CGI要用到的几个比较好的库,
    1.CGIC,ANSI C的CGI库 http://www.boutell.com/cgic/
    2.Sqlite,ANSI C的小型数据库 http://www.sqlite.org
    3.GD库,C语言的 图形库 http://www.boutellcom/gd/

    本来使用.NET+ SQLite的DataProvider,分页+绑定的时间已经达到了2000毫秒,但是被NW发现中文显示乱码,查阅SQLite官方网站发现连接串要指明使用UTF-8的编码,照作之后,乱码依旧。
       之后使用了SQLite命令行以及Delphi的SQLite组件进行中文查询以及显示,都没有问题,发现Delphi中我所使用的是ISO8859的字符集,猜想可能需要跟SQLite的字符集统一才可以,当然也不排除.net组件的bug的原因,恰好NW认为这个数据库不该由ASP.NET直接连接,就产生了利用DELPHI编写AutoMation对象进行查询的想法。
       查阅SQLite的官方网站关于语法的说明,想看看是否支持TOP以减小数据量,发现了好东西:他的SELECT语法包含了两个关键字:Limit和Offset,Limit后面加数字,实现了Top的功能,而Offset则可以指定跨越的记录数量,因此,分页变得异常简单。
       Automation对象完成之后,查询速度令我很惊讶:一个页面只用几百毫秒就可以搞定。开始很喜欢SQLite了。

       从表中检索数据。

    语法:
    sql-statement ::=    SELECT [ALL &line; DISTINCT] result [FROM table-list]
    [WHERE expr]
    [GROUP BY expr-list]
    [HAVING expr]
    [compound-op select]*
    [ORDER BY sort-expr-list]
    [LIMIT integer [( OFFSET &line; , ) integer]]

      1. File &line; New &line; Projects: Win32 Console Application输入你自己的工程名这里是“D:\\MyTest”,然后选择An empty project,确定
      2. File &line; New &line; Files: C++ Source Files创建新文件Test.C
      3. 复制SQLite3从这里开始一文中的源文件
      4. Tools &line; Options…:Directorys向Include Files添加sqlite3.h(sqlite3.h sqlite3.c可以从官方网站上下载http://www.sqlite.org/sqlite-source-3_3_17.zip)所在路径,本例中为D:\\SQLite,然后再添加引用目标链接库(它的生成见下面生成引用目标链接库,也可参考SQLite如何在Windows下编译一文),本文中为D:\\SQLite
      5. 此时编译仍会提示test.obj : error LNK2001: unresolved external symbol _sqlite3_free
         test.obj : error LNK2001: unresolved external symbol _sqlite3_exec
         test.obj : error LNK2001: unresolved external symbol _sqlite3_close
         test.obj : error LNK2001: unresolved external symbol _sqlite3_errmsg
         test.obj : error LNK2001: unresolved external symbol _sqlite3_open
         Debug/MyTest.exe : fatal error LNK1120: 5 unresolved externals
      6. 因为不能找到链接库,Project &line; Settings… &line; Link: Object/Library Modules:后面添加sqlite3.lib,再编译通过。也可以在Test.C中添加#pragma comment(lib, "sqlite3.lib")实现相同的效果。
      7. 享受你的结果吧,呵呵:-)

    生成引用目标链接库

    用下面的命令实现为MS Visual C++从sqlitedll-3_3_17.zip(http://www.sqlite.org/sqlitedll-3_3_17.zip)创建一个导入库:

    LIB /DEF:sqlite.def

    它将生成sqlite.lib和sqlite.exp文件。sqlite.lib能被用来链接到你你的程序中以使用SQLite DLL。注意要将DLL的路径变量加入到你操作系统变量中。

    Enjoy youself!

    Sqlite wrapped
    : a C++ wrapper for the Sqlite database C API

    有趣Object Persistent方案。
    http://litesql.sourceforge.net/

    Features

       * C++ wrapper for sqlite
       * all the good stuff of sqlite
       * light persistence layer with relation support
       * automatic database schema creation and upgrading from C++ classes
       * small code base: less than 2500 lines of C++
       * create complex SQL queries using compile-time checked class API; minimizes need to write SQL query strings

    按文档,做一个Persistent类的步骤如下:
    一、继承 Persistent
    class OwnPersistent : public Persistent &leftsign;&rightsign;;

    二、使用宏PERSISTENT_BASE声明哪些变量需要Persistent
    class OwnPersistent : public Persistent &leftsign;
       PERSISTENT_BASE(OwnPersistent, 1, name, TEXT);
    &rightsign;;
    其中,第一个参数是类名,第二个参数表示后面有多少个变量,后面两个两个参数为一组,描述每一个变量。

    三、可以用RELATIONS宏描述类之间关联
    RELATIONS(object, relnum,
            rel1type, rel1from, rel1to, rel1id, rel1bidir, rel1name,
            rel2type, rel2from, rel2to, rel2id, rel2bidir, rel2name, …)

    其中的 relntype可以为以下几种:
    OORelation : one-to-one relation
    OMRelation : one-to-many relation
    MORelation : many-to-one relation
    MMRelation : many-to-many relation

    relnfrom、relnto是说从哪个类映射到哪个类
    relnid是映射关系的编号
    relnbidir是指定映射是否双向(只有当from和to是同一个类的时候可以使用)
    relnname映射关系的名字

    例如:
    class Person : public Persistent &leftsign;
       PERSISTENT_BASE(Person, 1, name, TEXT);
       RELATIONS(Persistent, 3,
                 OORelation, Person, Person, 1, false, mother,
                 OORelation, Person, Person, 2, false, father,
                 MMRelation, Person, Person, 3, true, friends);
    &rightsign;;

    最后就是声明cleanUp函数了,这里看得不是很明白,呵呵。

    最后的结果就是:
    class Person : public Persistent &leftsign;
       PERSISTENT_BASE(Person, 1, name, TEXT);
       RELATIONS(Persistent, 3,
                 OORelation, Person, Person, 1, false, mother,
                 OORelation, Person, Person, 2, false, father,
                 MMRelation, Person, Person, 3, true, friends);
        virtual void cleanUp() &leftsign;
            mother.flush();
            father.flush();
            friends.flush();
        &rightsign;
    &rightsign;;

    Person bill(db), bob(db);
    bill.name = "Bill";
    bill.update();

    bob.name = "Bob";
    bob.update();
    // both objects must be stored in database before they can be linked
    bill.friends.link(bob);
    // following statement would throw an exception because they are already friends
    bob.friends.link(bill);

    Person bob = bill.friends.fetchOne(Person::name_() == "Bob");
    vector<Person> billsFriends = bill.friends.fetch();

    效果的确有趣。不过没有仔细看具体实现。按作者自己说难度之一就是实现这种不定参数的宏。

    标签:,
    20070820 uclinux sqlite error - 五月 24, 2008 by yippee

    20070820 uclinux sqlite error
    http://www.yippeesoft.com

    http://blog.iyi.cn/hily/archives/2006/10/sqlite.html
    http://www.potu.com/reader/itempl4672609.html
    http://www.sqlite.com.cn/POParticle/6/84.Html

    求救:arm-uclibc-gcc编译SQLite的问题

    想把SQLite移植到ARM-uClinux上, 按照版上贴的移植方法进行

    版本为: sqlite-3.3.17
    由于之前多是基于arm-linux-gcc编译的, 将Makefile中有关arm-linux-的地方全换成了arm-uclibc-
    maik.mk, os.c, shell等文件也进行了相应修改

    但最终没有编译成功! 提示错误:
    libsqlite3.a(os_unix.o):in fuction \’sqlite3UnixDlopen\’:
    os_unix.o(.text+0xfb4):undefined reference to \’dlopen\’
    libsqlite3.a(os_unix.o): In function \’sqlite3UnixDlsym\’:
    os_unix.o(. text+0xfc8): undefined reference to \’dlsym\’
    libsqlite3.a(os_unix.o): In function \’sqlite3UnixDlclos\’:
    os_unix.o(. text+)xfdc): undefined reference to \’dclose\’
    collect3: ld returned 1 exit status
    make: ***[sqlite3] Error 1

    I followed to below order to crosscompile the source but the end I get some undefined reference errors.

    Do you have any idea how to solve this problem.

    Note: There is no problem when I try to crosscompile ver. 2.8.17. Every thing works great.

    **********************
    rm tclsqlite.c

    PATH=/usr/local/opt/crosstool/arm-linux/gcc-3.3.4-glibc-2.3.2/arm-linux/bin/:$PATH

    for i in *.c; do arm-gcc -O -c $i; done

    rm shell.o

    ar cr libsqlite.a *.o

    ranlib libsqlite.a

    arm-gcc -o sqlite shell.c libsqlite.a
    libsqlite.a(os_unix.o)(.text+0xf6c): In function `sqlite3UnixDlopen\’:
    : undefined reference to `dlopen\’
    libsqlite.a(os_unix.o)(.text+0xf78): In function `sqlite3UnixDlsym\’:
    : undefined reference to `dlsym\’
    libsqlite.a(os_unix.o)(.text+0xf84): In function `sqlite3UnixDlclose\’:
    : undefined reference to `dlclose\’
    collect2: ld returned 1 exit status

    > Jakub Ladman schrieb:
    > >> It\’s seems a bit strange to me that Makefile.linux-gcc includes tcl in
    > >> the build by default, but it does. Maybe that should change…
    > >>
    > >> If you add "-DNO_TCL" to the OPTS variable in Makefile.linux-gcc this
    > >> error should go away. i.e. add the following line somewhere after the
    > >> "OPTS = -DNDEBUG" bit:
    > >>
    > >> OPTS += -DNO_TCL
    Yes, i am idiot!!!!!!

    but after correction of this i get:

                    libsqlite3.a   -lpthread
    libsqlite3.a(os_unix.o): In function `sqlite3UnixDlopen\’:
    os_unix.c:(.text+0×848): undefined reference to `dlopen\’
    libsqlite3.a(os_unix.o): In function `sqlite3UnixDlsym\’:
    os_unix.c:(.text+0×85c): undefined reference to `dlsym\’
    libsqlite3.a(os_unix.o): In function `sqlite3UnixDlclose\’:
    os_unix.c:(.text+0×870): undefined reference to `dlclose\’
    collect2: ld returned 1 exit status
    make: *** [sqlite3] Error 1
    [EMAIL PROTECTED] ~/src/sqlite-3.3.13 $

     In function `dlfcn_load\’

    :dso_dlfcn.c:(.text+0×45): undefined reference to `dlopen\’
    :dso_dlfcn.c:(.text+0xc4): undefined reference to `dlclose\’
    :dso_dlfcn.c:(.text+0×102): undefined reference to `dlerror\’

    解决方法:

    在Makefile中的链接参数加上 -ldl就可以解决了

    http://www.ccw.com.cn/cio/research/program/htm2004/20041215_110V2.asp

    http://www.rzhome.net/blog/article.asp?id=11

    http://www.sqlite.org/quickstart.html

    http://blog.iyi.cn/hily/archives/2006/10/uclinuxberkeley_db_v4520.html

    http://www.ccw.com.cn/cio/research/program/htm2004/20041215_110V2.asp

    http://tech.sina.com.cn/other/2004-12-17/0840478378.shtml

    http://www.xxlinux.com/linux/article/development/embed/20051201/411.html

    http://www.potu.com/reader/itempl4672609.html

    标签:, , , , , , ,
    20070607 Finisar.SQLite - 二月 12, 2008 by yippee

    20070607 Finisar.SQLite
    http://www.yippeesoft.com

    用 SQLiteTables.exe 生成的可以 SQLite Database Browser.exe 不行
    unknown file format

    同样的一段代码,比如:
    SQLiteConnection dbConn = new SQLiteConnection("Data Source = sample.db3");
    SQLiteCommand dbCommand = new SQLiteCommand("Select * from [COUNTRY] ", dbConn);
    dbConn.Open();
    SQLiteDataReader dbReader = dbCommand.ExecuteReader();
    在Windows窗体开发中,没有任何问题;但在mobile 5中开发,出现错误:sqlite error:not such table country,百思不得其解,恳请赐教!

    初步找到原因和解决方法了:

    1、我的环境:SQLite ADO.NET 2.0 驱动程序用的是System.Data.SQLite.DLL(1.0.33.0),在VisualStudio2005上调试WindowMobile5.0

    2、执行select语句,出现no such table的错误,原来我的数据库是用SQLite Database Browser 1.2.1和1.3创建的,我改用代码里动态创建表、插入、查询,一点问题都没有。复制出创建的数据库到PC,再用SQLite Database Browser 1.3打开,可以看到创建的表和记录,然后我新建另外一个表,保存复制到手机,添加代码查询新表,PC上编译再复制到手机,手机上运行程序,又出现no such table的错误——看来,罪魁祸首就是SQLite Database Browser了,晕!

    3、解决方法:自个代码里建表,可以用SQLite Database Browser 1.3 PC上添加纪录,但不能建表。

    #region 用DataReader读sqlite数据库速度
       //   long ticks1  = DateTime.Now.Ticks;//开始
       //   SQLiteConnection sqliteConn = new SQLiteConnection(@"Data Source=….e2c.db;Version=3;Compress=true");       
       //   sqliteConn.Open();
       //   SQLiteCommand sqliteCmd = sqliteConn.CreateCommand();
       //   sqliteCmd.CommandText = "select English from English";
       //   SQLiteDataReader sqliteDr = sqliteCmd.ExecuteReader();
       //   ArrayList al = new ArrayList();
       //   while(sqliteDr.Read())
       //   &leftsign;
       //    al.Add(sqliteDr["English"]);
       //   &rightsign;
       //   long ticks2 = DateTime.Now.Ticks;//完成赋值到ArrayList
       //     
       //   this.listBox1.DataSource = al;
       //   long ticks3 = DateTime.Now.Ticks;//完成绑定到listBox
       //  
       //
       //   MessageBox.Show((ticks2-ticks1).ToString());
       //   MessageBox.Show((ticks3-ticks2).ToString());
       #endregion

       #region 用DataAdapter读sqlite数据库速度
       //   long ticks1 = DateTime.Now.Ticks;
       //  
       //   SQLiteConnection sqliteConn = new SQLiteConnection(@"Data Source=….e2c.db;Version=3;Compress=ture");
       //   sqliteConn.Open();
       //   SQLiteDataAdapter sqliteDa = new SQLiteDataAdapter("select English from English",sqliteConn);
       //   DataSet sqliteDs = new DataSet();
       //   sqliteDa.Fill(sqliteDs);
       //   long ticks2 = DateTime.Now.Ticks;
       //  
       //   this.listBox1.DataSource = sqliteDs.Tables[0].DefaultView;
       //   this.listBox1.DisplayMember = "English";
       //   long ticks3 = DateTime.Now.Ticks;
       //
       //   MessageBox.Show((ticks2-ticks1).ToString());
       //   MessageBox.Show((ticks3-ticks2).ToString());

       using System;using System.Web;using System.Threading;using System.Data;using System.Data.SqlClient;using System.Configuration;using Finisar.SQLite ;namespace BlackbeltBLL &leftsign;    public class BackgroundService : IHttpModule &leftsign;        static Timer timer;        int interval = 5000;        public String ModuleName &leftsign;             get &leftsign; return "BackgroundService"; &rightsign;         &rightsign;            public void Init(HttpApplication application) &leftsign;             // Wire-up application events            if (timer == null)                timer = new Timer(new
                 TimerCallback(ScheduledWorkCallback), application.Context, interval, interval);        &rightsign;        public void Dispose() &leftsign;            timer = null;        &rightsign;        private void ScheduledWorkCallback (object sender) &leftsign;            HttpContext context = (HttpContext) sender;            Poll(context);        &rightsign;        void DoSomething (HttpContext context) &leftsign;        &rightsign;        #region DB Poll        void Poll (HttpContext context) &leftsign;            SQLiteConnection connection = new
                  SQLiteConnection(context.Application["connstring"].ToString());            SQLiteCommand command = new
                 SQLiteCommand("select tableName, ChangeID from changenotifications",connection);     command.CommandType=CommandType.Text;           IDataReader reader;            string key = ConfigurationSettings.AppSettings["SqlDependency"];            connection.Open();            reader = command.ExecuteReader();            while (reader.Read()) &leftsign;                string tableKey = String.Format(key, reader["TableName"]);                if (context.Cache[tableKey] != null) &leftsign;                    int changeKey =
                          int.Parse( context.Cache[ String.Format(key, reader["TableName"])].ToString() );                    if (changeKey != int.Parse( reader["ChangeID"].ToString() ))                        context.Cache.Remove(tableKey);                &rightsign;   &rightsign;            connection.Close();        &rightsign;        #endregion &rightsign;&rightsign;

    Basically this just kicks off a background thread and polls your ChangeNotifications Table every X milliseconds, and if your changeId has been changed by your trigger because of an inserted record, it invalidates the Response Cache, forcing your page\’s code to actually "re-hit" the database to populate your DataSet (or whatever your specific business logic calls for).

    标签:,
    20070607 System.Data.SQLite.DLL cf2.0 cs0009 - 二月 11, 2008 by yippee

    20070607 System.Data.SQLite.DLL cf2.0 cs0009
    http://www.yippeesoft.com

    Microsoft.Common.targets : warning MSB3247: 同一依赖程序集的不同版本之间出现冲突。
    CSC : fatal error CS0009: 未能打开元数据文件“ \\SQLite.NET\\bin\\CompactFramework\\System.Data.SQLite.DLL”–“版本 2.0 不是兼容版本。”

    Visual C# Reference: Errors and Warnings
    Compiler Error CS0009

    Error Message
    Metadata file \’file\’ could not be opened — \’description\’

    The file specified with the /reference compiler option does not contain valid metadata.

    1、vs2005访问sqlite数据库需要使用ADO.NET 2.0 SQLite Data Provider控件,大家可以从http://sqlite.phxsoftware.com/ 下载最新的版本。下载后执行安装程序,默认安装到C:\\Program Files\\SQLite.NET目录中。
    2、进入C:\\Program Files\\SQLite.NET\\bin目录,可以找到一个System.Data.SQLite.DLL文件。稍后将此文件拷贝到vs2005项目中的bin目录。
    3、打开vs2005并新建一个C#语言的web项目,在代码页开头添加引用:using System.Data.SQLite;(或许你还需要在项目名那点右键然后“添加引用”该dll文件)
    4、数据库的连接语句格式为:strConn = @"Data Source=xxx.dat"; // xxx.dat为你所新建的数据库文件。连接成功后即可像访问其它SQL数据库一样对其进行操作。
    连接例子如下:
    using System.Data.SQLite;
    ….
    string strConn = @"Data Source=d:\\myweb\\test.dat" ;
    SQLiteConnection myCon = new SQLiteConnection(strConn);
    SQLiteDataAdapter myAda = new SQLiteDataAdapter("select * from test", myCon);
    DataSet mySet = new DataSet();
    myAda.Fill(mySet, "表名");

    CF 2.0 中sqlite开发问题

    同样的一段代码,比如:
    SQLiteConnection dbConn = new SQLiteConnection("Data Source = sample.db3");
    SQLiteCommand dbCommand = new SQLiteCommand("Select * from [COUNTRY] ", dbConn);
    dbConn.Open();
    SQLiteDataReader dbReader = dbCommand.ExecuteReader();
    在Windows窗体开发中,没有任何问题;但在mobile 5中开发,出现错误:sqlite error:not such table country,百思不得其解,恳请赐教!

    初步找到原因和解决方法了:

    1、我的环境:SQLite ADO.NET 2.0 驱动程序用的是System.Data.SQLite.DLL(1.0.33.0),在VisualStudio2005上调试WindowMobile5.0

    2、执行select语句,出现no such table的错误,原来我的数据库是用SQLite Database Browser 1.2.1和1.3创建的,我改用代码里动态创建表、插入、查询,一点问题都没有。复制出创建的数据库到PC,再用SQLite Database Browser 1.3打开,可以看到创建的表和记录,然后我新建另外一个表,保存复制到手机,添加代码查询新表,PC上编译再复制到手机,手机上运行程序,又出现no such table的错误——看来,罪魁祸首就是SQLite Database Browser了,晕!

    3、解决方法:自个代码里建表,可以用SQLite Database Browser 1.3 PC上添加纪录,但不能建表。

    Fatal error CS0009: Metadata file XXX.DLL could not be opened…

    Problem

    You receive this error when compiling your application:

    Fatal error CS0009: Metadata file ‘XXX.dll\’ could not be opened — \’There isn\’t metadata in the memory or stream\’

    This problem occurs when you have added a third-party DLL to your application and have not properly added it to your compiler’s project file or references list.
    Solution

    Open your project in Visual Studio .NET.  Make sure the DLL exists and has been properly added to the reference list.  If you are using VBC or CSC to compile your project, check your application’s CompileApplication.rsp file to make sure the DLL is in the /references list like the other DLL’s.

    Your DLL may not be compatible with .NET or with .NET’s 32-bit mode.  Ensure that your DLL is .NET compatible.

    If your project still won’t compile properly, try switching your application’s compiler selection in Iron Speed Designer’s Application Wizard from \’vbc.exe\’  or ‘csc.exe’ to Visual Studio .NET or vice versa.  Using Visual Studio .NET will take longer to build than .NET’s VBC or CSC built-in compilers, but Visual Studio .NET will resolve all of the references properly without having to change your application’s CompileApplication.rsp file.
    See Also

    System.Data.SQLite is an enhanced version of the original SQLite database engine.  It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll).  It has no linker dependency on the .NET runtime so it can be distributed independently of .NET, yet embedded in the binary is a complete ADO.NET 2.0 provider for full managed development.

    标签:, , ,
    20070504 sqlite smartphone 2003 vs2005 - 一月 18, 2008 by yippee

    20070504 sqlite smartphone 2003 vs2005
    http://www.yippeesoft.com

    基本实现SQLITE的访问
    TCHAR szFile[MAX_PATH];
           TCHAR szPath[MAX_PATH];
           GetModuleFileName(NULL,szFile,MAX_PATH);
           size_t i;
           for(i=lstrlen(szFile)-1; i>0 && szFile[i]!=\’\\\\\’; i–);
               szFile[i]=\’\\0\’;

    感觉这样分割路径,不是很好,这是ANSI的做法,UNICODE看上去可以,不过不知道有没有后遗症
    最好用 http://www.yippeesoft.com

    Break a path name into components. These functions are deprecated because
    more secure versions are available, see _splitpath_s,
    _wsplitpath_s
    .

           lstrcpy(szPath,szFile);
           lstrcat(szPath,_T("\\\\YippeeMoneySp.db"));
           m_info=szPath;
           m_info+="\\r\\n";

           CppSQLite3DB db;
           db.open(szPath);
           CppSQLite3Query q = db.execQuery(_T("select * from test;"));
           for (int fld = 0; fld < q.numFields(); fld++)
           &leftsign;
               m_info+= q.fieldName(fld);
               m_info+="(" ;
               m_info+=+ q.fieldDeclType(fld);
               m_info+=+ ")&line;";
           &rightsign;
           m_info+= "\\r\\n";

           while (!q.eof())
           &leftsign;
               m_info+= q.fieldValue(0) ;
               m_info+= "&line;\\r\\n";
               
               q.nextRow();
           &rightsign;
           UpdateData(FALSE);
       
    采用
    http://softvoile.com/development/CppSQLite3U/

    有个小问题
    int CppSQLite3DB::execScalar(LPCTSTR szSQL)
    &leftsign;
       CppSQLite3Query q = execQuery(szSQL);

       if (q.eof() &line;&line; q.numFields() < 1)
           throw CppSQLite3Exception(CPPSQLITE_ERROR, _T("Invalid scalar query"),    DONT_DELETE_MSG);

       return _tstoi(q.fieldValue(0));
    &rightsign;

    报告:
    .\\CppSQLite3U.cpp(293) : error C2664: \’atoi\’ : cannot convert parameter 1 from \’LPCTSTR\’ to \’const char *\’
           Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

    Return Value
    Each function returns the int value produced by interpreting the input characters as a number. The return value is 0 for atoi and _wtoi, if the input cannot be converted to a value of that type.

    In Visual C++ 2005, in the case of overflow with large negative integral values, LONG_MIN is returned. atoi and _wtoi return INT_MAX and INT_MIN on these conditions. In all out-of-range cases, errno is set to ERANGE. If the parameter passed in is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, these functions set errno to EINVAL and return 0.

    Remarks
    These functions convert a character string to an integer value (atoi and _wtoi). The input string is a sequence of characters that can be interpreted as a numerical value of the specified type. The function stops reading the input string at the first character that it cannot recognize as part of a number. This character may be the null character (\’\\0\’ or L\’\\0\’) terminating the string.

    The str argument to atoi and _wtoi has the following form:

    [whitespace] [sign] [digits]]

    A whitespace consists of space or tab characters, which are ignored; sign is either plus (+) or minus (–); and digits are one or more digits.

    The versions of these functions with the _l suffix are identical except that they use the locale parameter passed in instead of the current locale.

    TCHAR.H routine  _UNICODE & _MBCS not defined  _MBCS defined  _UNICODE defined  
    _tstoi
    atoi
    atoi
    _wtoi

    _ttoi
    atoi
    atoi
    _wtoi

    干脆改为 _WTOI OK

    http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers

    标签:, , , , ,
    20070810 smartphone sqlite - 一月 11, 2008 by yippee

    20070810 smartphone sqlite
    http://www.yippeesoft.com

    同事作终端,用了SQLITE,可是数据库操作有点慢
    我问了一下,结果同事说底层软件不能和PC比什么的
    我觉得作为一个嵌入式数据库,也不可能太慢

    找了找资料
    硬件配置上,MPX220采用了ARM4 OMAP1611的204MHz CPU

    sqlite支持大部分sql92标准,创建表时注意下面几点:
    先给个普遍使用的sql语句:CREATE TABLE "user" ("uid" integer PRIMARY KEY , "name" varchar (50) NOT NULL , "password" varchar (32) NOT NULL)
    这里注意几点:
    “INTEGER PRIMARY KEY”,表示自动增长的id,插入行时留空就能自动增长,如:INSERT INTO "user" ("uid", "name", "password") VALUES (NULL, \’name\’, \’pssword\’),或者INSERT INTO "user" ("name", "password") VALUES (\’name\’, \’pssword\’),另外sqlite允许插入被删除的id,如:DELETE FROM "user" WHERE "uid" = 0; INSERT INTO "user" ("uid", "name", "password") VALUES (1, \’name\’, \’pssword\’),

    在插入数据和查询时都会经常遇到单引号(\’)的问题,轻则查询出错,重则导致sql注入,sqlite插入\’和mssql一样,使用\’\'来插入,同样不能插入(\\0),使用时比较简单的方法就是使用php自带的函数(sqlite_escape_string)来格式化,可以参考后面我给的类,注意sqlite_escape_string格式化时比较特别,不是只是简单的把\’转为\’\',具体可以查看php的帮助文档。

    有没有注意到"user"呢,这里用双引号(")包括起来,在我们平时比较常见的mssql里是用[]来标记,mysql是用“来标记,不过sqlite比较。。。不知道怎么形容,看例子:
    CREATE TABLE \’user\’ (\’uid\’ integer PRIMARY KEY , \’name\’ varchar (50) NOT NULL , \’password\’ varchar (50) NOT NULL)
    CREATE TABLE "user" ("uid" integer PRIMARY KEY , "name" varchar (50) NOT NULL , "password" varchar (32) NOT NULL)
    CREATE TABLE [user] ([uid] integer PRIMARY KEY , [name] varchar (50) NOT NULL , [password] varchar (32) NOT NULL)
    上面3条语法都是可以的。
    这里注意下,在mssql环境中我们有时候是使用CREATE TABLE [user] ([uid] [int] PRIMARY KEY , [name] [varchar] (50) NOT NULL , [password] [varchar] (32) NOT NULL),就是字段类型中我们可以使用[]来包括起来,而在sqlite下是不行的。另外还有地方:CREATE INDEX user_name ON "user" ("name"),发现没有,索引中的名字没有用"包括起来,不知道怎么搞的。。如果用了"或\’或[]就不能正常索引了貌似。

    这是PC上的
    try
    &leftsign;
         //Connection string
         string connString = String.Format("Data Source=&leftsign;0&rightsign;;New=False;Version=3", DB_NAME);
         
         //Connecting database
         SQLiteConnection sqlconn = new SQLiteConnection(connString);
         
         //Open the connection
         sqlconn.Open();

         //Query
         string CommandText = "Select name from sqlite_master;";

         //SQLiteDataAdapter to fill the DataSet
         SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(CommandText, sqlconn);
         dataAdapter.Fill(ds);

         //Get the collection of rows from the DataSet
         DataRowCollection dataRowCol = ds.Tables[0].Rows;

         //Add the tables available in the DB to the combo box
         foreach (DataRow dr in dataRowCol)
         &leftsign;
             tablecombobox.Items.Add(dr["name"]);
         &rightsign;
         
         //Close the Connection
         sqlconn.Close();

    &rightsign;              
    catch (SQLiteException sqlex)
    &leftsign;
       MessageBox.Show(sqlex.Message);
    &rightsign;

    手机:
    SQLiteConnection conn = new SQLiteConnection();
               conn.ConnectionString = "Data Source=\\\\Storage\\\\Program Files\\\\t2\\\\test1.db;Version=3;New=False;Compress=True;";
               conn.Open();
               if (conn.State != ConnectionState.Open)
                   return;
               SQLiteCommand cmd = conn.CreateCommand();
               cmd.CommandText = "select sff from sf where ss=\’"+textBox2.Text+"\’";
               IDataReader r= cmd.ExecuteReader();

               if (r.Read())
               &leftsign;
                   textBox1.Text=r.GetString(0);
               &rightsign;

    用VS2005的设备仿真器倒是和ACTIVESYNC连接了,可是该死的VS2003却没有办法进行TCP连接

    例如
    string time=DateTime.Now.ToString("yyyyMMddHHmmss");
    DateTime dt=Convert.ToDateTime(time);
    后面那句怎么改,才会成功转换回来?
    DateTime dt = DateTime.ParseExact(time,"yyyyMMddHHmmss",System.Globalization.CultureInfo.CurrentCulture);

    例如  
     —–表———  
     id     name     age   sex  
     1       tom       18     male  
     —————-  
     如何实现如果表中存在   name   =“tom”则更新   age   =   20  
     如果没有的话,则插入一条新的记录。
     string   sql   =   @"  
     IF   EXISTS   (SELECT   *   FROM   表   WHERE   [name]=\’tom\’)  
         UPDATE   …  
     ELSE  
         INSERT   …  
     END  
     ";  

     SqlCommand   cmd   =   new   SqlCommand("select   count(*)   from   theTable   where   [name]=\’tom\’",   cn);  
     int   c   =   int.Parse(cmd.ExecuteScalar().ToString());  
     
     if   (c   >0)  
     &leftsign;  
     //更新  
     &rightsign;  
     else  
     &leftsign;  
     //插入  
     &rightsign;

     string   sql   =   @"  
     IF   EXISTS   (SELECT   *   FROM   [表]   WHERE   [name]=\’tom\’)  
         UPDATE   [表]   SET   [age]=20   WHERE   [name]=\’tom\’  
     ELSE  
         INSERT   INTO   [表]   ([name],[age],[sex])   VALUES   (\’tom\’,20,\’male\’)  
     END  
     ";  
     
     一条SQL语句就足够了,   用不着象楼上的那么麻烦.  

     string   sql   =   @"  
     IF   EXISTS   (SELECT   *   FROM   [表]   WHERE   [name]=\’tom\’)  
         UPDATE   [表]   SET   [age]=20   WHERE   [name]=\’tom\’  
     ELSE  
         INSERT   INTO   [表]   ([name],[age],[sex])   VALUES   (\’tom\’,20,\’male\’)  
     END  
     ";  
     
     或者可以写在存储过程里

     还不如简单一点  
     直接先做一个Delete,然后Insert  
     
     如果存在,删除后新增,逻辑上没有问题,结果也是正确的  
     如果不存在,删除语句不作任何影响,再添加,效果相同  
     
     反正2次数据库操作是必然的了  
     那又何必多做一次无意义的If运算呢
     文件操作

    若要执行此操作… 请参阅本主题中的示例…
    创建文本文件 向文件写入文本  
    写入文本文件 向文件写入文本  
    读取文本文件 从文件读取文本  
    向文件中追加文本 File.AppendText FileInfo.AppendText  
    重命名或移动文件 File.Move FileInfo.MoveTo  
    删除文件 File.Delete FileInfo.Delete  
    复制文件 File.Copy FileInfo.CopyTo  
    获取文件大小 FileInfo.Length  
    获取文件属性 File.GetAttributes  
    设置文件属性 File.SetAttributes  
    确定文件是否存在 File.Exists  
    读取二进制文件 对刚创建的数据文件进行读取和写入  
    写入二进制文件 对刚创建的数据文件进行读取和写入  
    检索文件扩展名 Path.GetExtension  
    检索文件的完全限定路径 Path.GetFullPath  
    检索路径中的文件名和扩展名 Path.GetFileName  
    更改文件扩展名 Path.ChangeExtension  

    目录操作

    System.IO 类

    目录操作
    string[] drives = Directory.GetLogicalDrives(); //本地驱动器的名,如:C:\\等
    string path = Directory.GetCurrentDirectory();    //获取应用程序的当前工作目录
    Path.GetFileName(@"c:\\dir\\file.txt");             //获取子目录的名字,result的结果是file.txt
    Directory.GetFiles(路径及文件名)                  //获取指定目录中的文件名(文件列表)
    DirectoryInfo di = new DirectoryInfo(@"f:\\MyDir"); //构造函数创建目录
    DirectoryInfo di=Directory.CreateDirectory(@"f:\\bbs"); //创建对象并创建目录
    if (di.Exists == false) //检查是否存在此目录
    di.Create(); //创建目录
    DirectoryInfo dis = di.CreateSubdirectory("SubDir"); //以相对路径创建子目录
    dis.Delete(true); //删除刚创建的子目录
    di.Delete(true); //删除创建目录

    文件操作
    Directory.Delete(@"f:\\bbs2", true); //删除目录及其子目录和内容(如为假不能删除有内容的目录包括子目录)
    Directory.GetDirectories 方法 //获取指定目录中子目录的名称
    string[] dirs = Directory.GetDirectories(@"f:\\", "b*");
    Console.WriteLine("此目录中以b开头的子目录共&leftsign;0&rightsign;个!", dirs.Length);
    foreach (string dir in dirs) &leftsign; Console.WriteLine(dir); &rightsign;
    Directory.GetFileSystemEntries //获取指定目录中的目录及文件名
    Directory.GetLogicalDrives //检索此计算机上格式为“<驱动器号>:\\”的逻辑驱动器的名称,【语法同上】
    Directory.GetParent //用于检索父目录的路径。
    DirectoryInfo a = Directory.GetParent(path);
    Console.WriteLine(a.FullName);Directory.Move //移动目录及其在内的所有文件
    Directory.Move(@"f:\\bbs\\1", @"f:\\bbs\\2"); //将文件夹1内的文件剪到文件夹2内 文件夹2是刚创建的

    Stream // 对字节的读写操作(包含对异步操作的支持) Reading Writing Seeking

    BinaryReader和BinaryWriter // 从字符串或原始数据到各种流之间的读写操作

    FileStream类通过Seek()方法进行对文件的随机访问,默认为同步

    TextReader和TextWriter //用于gb2312字符的输入和输出

    StringReader和StringWriter //在字符串中读写字符

    StreamReader和StreamWriter //在流中读写字符

    BufferedStream 为诸如网络流的其它流添加缓冲的一种流类型.

    MemoryStream 无缓冲的流

    NetworkStream 互联网络上的流

    //编码转换
    Encoding e1 = Encoding.Default;               //取得本页默认代码
    Byte[] bytes = e1.GetBytes("中国人民解放军"); //转为二进制
    string str = Encoding.GetEncoding("UTF-8").GetString(bytes); //转回UTF-8编码

    标签:, , , ,