参考的是http://blog.csdn.net/ym19860303/article/details/8531998这篇文章来学习的,同时也有同事的帮忙,写下来的目的是为了防止某一天自己忘记了,可以回来看看。
首先用cocos2dx3.9创建了一个项目newhello,之后导入down下来的sqlite3(不要schell.c)添加完后,如图:
setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
this->addChild(label, 1);
auto sprite = Sprite::create("HelloWorld.png");
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
this->addChild(sprite, 0);
readTable();
return true;
}
void HelloWorld::readTable()
{
std::string fullDBPath = FileUtils::getInstance()->getWritablePath() + "save.db";
CCLOG("fullPath : %s",fullDBPath.c_str());
//打开数据库
DBUtil::initDB(fullDBPath.c_str());
//创建表
// std::string createTableSql = "create table zuma (id integer primary key autoincrement,name char(10),age int,score int);"; //创建表,设置ID(此处为integer)为主键primary key,且自动增加autoincrement
std::string createTableSql = "create table stuInfo (id int ,name char(10),age int,score int);";
DBUtil::createTable(createTableSql.c_str(),"stuInfo");
//向表格中插入数据
std::string sqlss = "insert into stuInfo (id,name,age,score) values (1601,'张三',19,90)";
/* 插入一条数据 */
DBUtil::insertData(sqlss);
// 更新
std::string updateString = "update stuInfo set score = 95;";
DBUtil::updateData(updateString);
/* 查询数据 */
std::string selectStr = "select * from stuInfo";
//DBUtil::getDataInfo(selectStr, 0);
StudentInfo studentInfo;
studentInfo.nID = 1601;
DBUtil::getDataInfo(selectStr, &studentInfo);
studentInfo = DBUtil::m_studentInfo;
CCLOG("id = %d",studentInfo.nID);
CCLOG("name = %s",studentInfo.sName.c_str());
CCLOG("age = %d",studentInfo.nAge);
CCLOG("score = %d",studentInfo.nScore);
/* 不能忘记关闭数据库 */
DBUtil::closeDB();
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
之后运行Xcode后,显示打印信息为
fullPath : /var/mobile/Containers/Data/Application/1F7B08E5-36C1-4C00-B89B-D900EA35A1EC/Documents/save.db
不存在创建表
id= 1601
n_column:4
id:1601 name:张三 age:19 score:95
id = 1601
name = 张三
age = 19
score = 95
2016-01-19 14:44:22.061 newhello-mobile[6059:1366321] cocos2d: surface size: 1136x640
ok,完了,最后再上传一份完整的项目代码,(上传完居然显示不出来,好吧,以后再上传)贴上地址:
例子的开门钥匙