该文转载自 http://my.oschina.net/memorybox/blog/67616
easySQLite是一个sqlite的C++封转库,非常简洁。适合于小型项目,将它的帮助文档翻译了一下,推荐之。
项目地址:http://code.google.com/p/easysqlite/
easySQLite--a C++ SQLite wrapper
这是一个SQLite C 数据引擎接口的C++封装库。它的结构非常简单,您可以很轻松的通过它来操纵本地数据库文件
easySQLite 授权方式为BSD License.
easySQLite 在Visual C++ 2010 Express环境下通过测试,但它并不依赖于非标准特性,所以您可以使用任意C++编译器来编译它。
怎样使用?
首先,请在项目中包含"SqlCommon.h" ,如果您需要其他组件支持的话,请包含相应的头文件。
easySQLite 使用命名空间: sql 。
然后,您需要用Field 对象定义一个表结构。
Field definition_tbPerson[] =
{
Field(FIELD_KEY),
Field("fname", type_text, flag_not_null),
Field("lname", type_text, flag_not_null),
Field("birthdate", type_time),
Field(DEFINITION_END),
};
Field构造函数默认需要如下参数:
- name
(sql::string) - type
(sql::field_type) - flags
(sql::field_flags). Can be OR'ed
数据表定义必须以 "Field(FIELD_KEY) "开头,以"Field(DEFINITION_END)"结尾。
Field(FIELD_KEY) 可以看做 Field("_ID", type_int, flag_primary_key).
现在,您可以打开/创建数据库文件了。就是先定义一个Database对象,然后打开进行操作。
sql::Database db; try { db.open("test.db"); //... } catch (Exception e) { //... }
TIP: 您可以通过返回值或者 ::errMsg() 函数来检查错误。 大多数类的错误检查是通过异常来实现的
您可以在"SqlCommon.h "中关闭 USE_EXCEPTIONS 检测,将它改为 "manually"就可以通过返回值来排错,例如:
if (!db.open("test.db")) { log(db.errMsg()); }
数据库的准备工作完成后,下一步就是定义数据表:
sql::Table tbPerson(db.getHandle(), "person", definition_tbPerson);
sql::Table的构造函数默认参数为:
- db handle
(sqlite3*) - tableName
(sql::string) - fields definition
(sql::Field*). Field* array or FieldSet* of another table.
现在,您可以通过Table对象来操作数据库了,例如:
//remove table from database if exists if (tbPerson.exists()) tbPerson.remove(); //create new table tbPerson.create(); //removes all records tbPerson.truncate(); //loads all records to internal recordset tbPerson.open(); //loads one record tbPerson.open("_ID == 5"); //returns loaded records count tbPerson.recordCount();
如何修改或添加/删除数据
如果要修改/添加/删除数据,您可以使用Record对象来完成。
要添加(insert)一条数据的话,先凭借数据表的FieldSet 定义一个Record对象,然后修改Record对象,最后将其插入到数据表中。
Record record(tbPerson.fields()); record.setString("fname", "Jan"); record.setString("lname", "Kowalski"); record.setTime("birthdate", time::now()); tbPerson.addRecord(&record);
下面演示如何修改数据:
tbPerson.open("_ID >= 10 and _ID <= 15"); for (int index = 0; index < tbPerson.recordCount(); index++) { if (Record* record = tbPerson.getRecord(index)) { record->setString("fname", ""); record->setString("lname", "Nowak"); record->setNull("birthdate"); tbPerson.updateRecord(record); } }
下面演示如何列出所有数据:
tbPerson.open(); for (int index = 0; index < tbPerson.recordCount(); index++) if (Record* record = tbPerson.getRecord(index)) log(record->toString());
下面演示如何列出指定_ID的数据:
if (Record* record = tbPerson.getRecordByKeyId(7)) { //... }
您可以参考easySQLite.cpp文件获得更多的示例。
Author
Copyright (c) 2010, Piotr Zagawa
All rights reserved.
translator
memorybox 2012/07/17