SQLite集成与用法
概述
在Cocos2d-x中,简单数据存储,可以使用UserDefault。那么如何存储大量,不规则的数据?我们可以使用SQLite数据库存储数据。SQLite是使用非常广泛的嵌入式数据库,它有小巧 、高效、跨平台、开源免费和易操作的特点。
SQLite数据库是使用C语言来编写的,那么在Cocos2d-x使用SQLite也是得心应手。
准备
首先创建一个Cocos2d-x v3.x的helloworld工程,我们将以该工程作为SQLite集成与用法的实战工程。
打开终端,使用如下命令新建工程:
1
|
cocos
new
HelloWorld -p com.your_company.HelloWorld -l cpp
|
按照上面的操作,我们新建了一个Cocos2d-x v3.x的HelloWorld工程。
iOS/Mac
iOS/Mac的系统库自带sqlite库,我们只需添加libsqlite3.0.dylib库即可。
Android
Android系统没有自带sqlite库,我们需要手动添加。
1.下载sqlite包
下载地址:http://www.sqlite.org/download.html下载后,在项目中导入sqlite3.c和sqlite3.h两个文件即可。
2.导入到工程
3.修改Android.mk
使用SQLite
打开HelloWorldScene.cpp文件,我们在里面加入SQLite的使用示例
引入头文件
创建SQLite 数据库
sqlite3 *pdb=NULL;
//1
std::string path= FileUtils::getInstance()->getWritablePath()+
"save.db"
;
//2
std::string sql;
int
result;
result=sqlite3_open(path.c_str(),&pdb);
//3
if
(result!=SQLITE_OK)
{
log
(
"open database failed,number%d"
,result);
}
|
- 数据库指针
- 指定数据库的路径
- 打开一个数据库,如果该数据库不存在,则创建一个数据库文件
SQL语句
- 创建表的SQL语句
创建Table
result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL);
//1
(result!=SQLITE_OK)
"create table failed"
);
|
- 创建表
插入数据
"insert into student values(1,'student1','male')"
;
"insert data failed!"
);
"insert into student values(2,'student2','female')"
;
);
"insert into student values(3,'student3',monospace!important; font-size:1em!important; min-height:inherit!important">;
|