A simple Tutorial How to use SQLite in cocos2d-x ……(Tutorial by YUYE)

At first you need to home page download the “sqlite3.h” and “sqlite3.c” source code. I’ll apply it after this topic. u need add their to u projects

[cpp] view plaincopy

sqlite3 *pdb=NULL;  
std::string path=CCFileUtils::sharedFileUtils()->getWriteablePath()+"save.db3";  


std::string sql;  
int result;  
result=sqlite3_open(path.c_str(),&pdb);  
if(result!=SQLITE_OK)  
    CCLog("open database failed,  number%d",result);  

if you are in android platform please using

std::string dbPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("save.db3");

#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
        dbPath  = CCFileUtils::sharedFileUtils()->getWritablePath();
        dbPath  += "/save.db3";

        FILE* file = fopen(dbPath.c_str(), "r");
        if (file == nullptr)
        {
            unsigned long size;
            const char* data = (char*) CCFileUtils::sharedFileUtils()->getFileData("dict.db", "rb", &size);
            file = fopen(dbPath.c_str(), "wb");
            fwrite(data, size, 1, file);
            CC_SAFE_DELETE_ARRAY(data);
        }
        fclose(file);
#endif

Above code created SQLite database file. Attention: you need give the path for SQLite database file

[cpp] view plaincopy

result=sqlite3_exec(pdb,"create table student(ID integer primary key autoincrement,name text,sex text)",NULL,NULL,NULL);  
if(result!=SQLITE_OK)  
    CCLog("create table failed");  

Here was created table for SQL query
[cpp] view plaincopy

sql="insert into student  values(1,'zhycheng','male')";  
result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);  
if(result!=SQLITE_OK)  
    CCLog("insert data failed!");  



sql="insert into student  values(2,'liuyali','female')";  
result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);  
if(result!=SQLITE_OK)  
    CCLog("insert data failed!");  

sql="insert into student  values(3,'zhy_cheng','male')";  
result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,NULL);  
if(result!=SQLITE_OK)  
    CCLog("insert data failed!");  

asserting data

[cpp] view plaincopy

sql="delete from student where ID=1";  
result=sqlite3_exec(pdb,sql.c_str(), ,NULL,NULL);  
if(result!=SQLITE_OK)  
    CCLog("delete data failed!");  

Deleting Data

[cpp] view plaincopy

char **re;  

int r,c;  

sqlite3_get_table(pdb,"select * from student",&re,&r,&c,NULL);  

CCLog("row is %d,column is %d",r,c);  

CCLabelTTF *liu=CCLabelTTF::create(re[2*c+1],"Arial",24);  
liu->setPosition(ccp(200,200));  
addChild(liu,1);  
CCLog(re[2*c+1]);  


sqlite3_free_table(re);  

sqlite3_close(pdb);  

Searching Data

we can print the Result to Screen by a Label in Android.
Last, if u want to publish on Android. u need to modify the MK file. the path is proj.android/jin/Android.mk。and u need add
sqlite3.c compile information like this way :

[cpp] view plaincopy

LOCAL_PATH := $(call my-dir)  

include $(CLEAR_VARS)  

LOCAL_MODULE := game_shared  

LOCAL_MODULE_FILENAME := libgame  

LOCAL_SRC_FILES := hellocpp/main.cpp \  
                   ../../Classes/AppDelegate.cpp \  
                   ../../Classes/HelloWorldScene.cpp\  
        ../../Classes/sqlite3.c  

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes                     

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static  

include $(BUILD_SHARED_LIBRARY)  

$(call import-module,CocosDenshion/android) \  
$(call import-module,cocos2dx) \  
$(call import-module,extensions)  

h3.you need save data in this path /data/data/com.zhycheng.SQLiteTest/save.db3。

if you have any question please u can reply this topic and you can download the demo project in my github

4 Likes

Looks a bit challenging. Somehow similar to those generic SQLs but with variations. Good Luck to Me! -
All State Van Lines Relocation

I hope my tutorials can help you .if you need more help please just let us know.cocos2d-x team will try our best to help you. Although my poor english confuse you too much.
Clark Wayne wrote:

Looks a bit challenging. Somehow similar to those generic SQLs but with variations. Good Luck to Me! -
All State Van Lines Relocation

splite3 in my project not work on android. Help me yuye liu

I can help you on monday.
Tung Luong wrote:

splite3 in my project not work on android. Help me yuye liu

Yuye Liu can I ask how to open previously created database? How to add sqlite database to project and use it in game? Because if I am right you are creating a new blank database with C++. But I am asking how to use already created database?

Thanks for your tutorial and I am able to work on sqlite.
After some work, I found that using CppSQLite3 (c++ wrapper for sqlite) is better for handling existing db.

proj.win32 is OK but proj.android not work (only sqlite3)
Help me please! yuye liu

The db file should be copied to writeable folder. i don’t know why???
In my project:

std::string dbPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("dict.db");

#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
        dbPath  = CCFileUtils::sharedFileUtils()->getWritablePath();
        dbPath  += "/dict.db";

        FILE* file = fopen(dbPath.c_str(), "r");
        if (file == nullptr)
        {
            unsigned long size;
            const char* data = (char*) CCFileUtils::sharedFileUtils()->getFileData("dict.db", "rb", &size);
            file = fopen(dbPath.c_str(), "wb");
            fwrite(data, size, 1, file);
            CC_SAFE_DELETE_ARRAY(data);
        }
        fclose(file);
#endif

Tung Luong wrote:

proj.win32 is OK but proj.android not work (only sqlite3)
Help me please! yuye liu

Done.
zhu tang. Thankyou so much!

Thanks a lot.
zhu tang wrote:

The db file should be copied to writeable folder. i don’t know why???
In my project:
>

> std::string dbPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("dict.db");
>       
> #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
>       dbPath  = CCFileUtils::sharedFileUtils()->getWritablePath();
>       dbPath  += "/dict.db";
> 
>       FILE* file = fopen(dbPath.c_str(), "r");
>       if (file == nullptr)
>       {
>           unsigned long size;
>           const char* data = (char*) CCFileUtils::sharedFileUtils()->getFileData("dict.db", "rb", &size);
>           file = fopen(dbPath.c_str(), "wb");
>           fwrite(data, size, 1, file);
>           CC_SAFE_DELETE_ARRAY(data);
>       }
>       fclose(file);
> #endif
> 

>

Tung Luong wrote:
> proj.win32 is OK but proj.android not work (only sqlite3)
> Help me please! yuye liu

a little bit confusing to apply it on cross platform code.
would you please revise the sample code for the android part? thank you for help

ok , I’ll do it for you . thank you for your opinions.
winipcfg exe wrote:

a little bit confusing to apply it on cross platform code.
would you please revise the sample code for the android part? thank you for help

Need some help on android project.
Say if we have an existing DB file named data.db3, where should we put the file under folder “proj.android”? Thank you for help.

if you wan’t save database in proj.android/res/ it will be read only. Also you can copy it and save in writable path (you can get it from CCFileManager?)

There is no CCFileManager in Cocos2d-x or I can’t find one.

Can somebody share knowledge how he/she has got this to work on Android?

I’m trying with these steps,
first - code for Android database,
than code for opening database
and then for searching - all from examples in first post, but it seems that my database is empty. This line CCLog(“row is %d,column is %d”,r,c); gives me that there’re 0 rows and 0 columns. My database has extension sqlite and I build it in SQLite Manager add-on for Firefox. I’ve placed it in Resource folder. It has one row and 7 columns - I’m trying with small example, just to get it work. Can somebody help?

I’ve got this to work. I’m working with two databases with .sqlite extenstion. I’ve probably had problem with saving dbPath to global variable, and when result=sqlite3_open(path.c_str(),&pdb); was executed it created new empty database, so that’s why there was 0 rows and 0 columns.

How do I can import a big data? In native Android, I can import database from CSV file through SQLManager. How about in Cocos2dx? Thanks

@lolyoshi you must learn what is the JNI for android.

@yuye I run don’t have error but when i open db file. I don’t find student table. Can you help me?