Create SQLite database in Cocos2d-x, cocos2d-xsqlite

Source: Internet
Author: User

Create SQLite database in Cocos2d-x, cocos2d-xsqlite
The following describes how to create a MyNotes database through the API provided by SQLite3. Generally, the following three steps are required to create a database.
(1) Use the sqlite3_open function to open the database.
(2) Use the sqlite3_exec function to execute the Create Table statement and Create a database Table.
(3) Use the sqlite3_close function to release resources.
In this process, we use three SQLite3 API functions, all of which are pure C functions. In the Cocos2d-x through C ++ call C function is of course not a problem, NoteDAO. cpp in the NoteDAO: initDB () function can initialize the database, its related code is as follows:

int NoteDAO::initDB(){auto sharedFileUtils = FileUtils::getInstance();string path = dbDirectoryFile();①bool isExist = false;isExist = sharedFileUtils->isFileExist(path);②if (!isExist) {log("NotesList.sqlite3 doesn't exist.");return -1;}sqlite3* db= NULL;if (sqlite3_open(path.c_str(), &db) != SQLITE_OK) {③sqlite3_close(db);④CCASSERT(false, "DB open failure.");⑤} else {char *err;string createSQL = "CREATE TABLE IF NOT EXISTS Note (cdate TEXT PRIMARY KEY, content TEXT)";⑥if (sqlite3_exec(db,createSQL.c_str(),NULL,NULL,&err) != SQLITE_OK) {⑦sqlite3_close(db); ⑧CCASSERT(false, "Create table failure."); ⑨}sqlite3_close(db);⑩}return 0;}


The above code initDB () function is used to initialize the database function. This function is used to create tables and other objects in the database. It is called every time a CRUD operation is performed on the database. The processing process in this function is to first determine whether the database file NotesList. sqlite3 exists. If it does not exist, it is initialized. if it already exists, it will jump out of the function. In the code, line ① calls the dbDirectoryFile () function, which is a function encapsulated by us to obtain the full path of the database file NotesList. sqlite3 in the writable directory. The Code in line ② is used to determine whether the NotesList. sqlite3 database file can be written into the directory exists. If no program exists, it jumps out of the function.
The Code in line ③ is to create a database. The first parameter of the sqlite3_open function is the complete path of the database file. Note that the SQLite3 function accepts data of the const char * type, you need to use the c_str () function to convert string data to the const char * type, the second parameter is the address of the sqlite3 pointer variable db, and the return value is the int type. In SQLite3, we define many constants. If the return value is the same as the constant SQLITE_ OK, the creation is successful. If the database fails to be opened, we need to use the line 4 Code sqlite3_close (db) to stop the database from releasing resources. Similarly, there are the line 2 and the line 2 code. The fifth line of code uses the CCASSERT asserted macro. When the first parameter is false, an exception is thrown, the program is terminated, and the second parameter is output as the log Content.
Line 6 of the Code is to write an SQL statement for table creation. The Code is as follows:
Create table if not exists Note (cdate text primary key, content TEXT)
The create table statement, if not exists, can determine whether the table exists. IF the TABLE does NOT exist, it is created. IF the table exists, it is NOT created. If you use the create table statement, if the TABLE exists, data throws an exception. The first line of code is similar.
The Code in line 7 is to execute the table creation statement, in which the statement sqlite3_exec (db, createSQL. c_str (), NULL, NULL, & err) executes the SQL statement for table creation in Row 6. The first parameter of the sqlite3_exec function is the address of the sqlite3 pointer variable db, the second parameter is the SQL statement to be executed, the third parameter is the function to be called back, the fourth parameter is the parameter of the callback function, and the fifth parameter is the error message of execution error.
To be able to call the initialization database function initDB () in NoteDAO, we need to call it in the HelloWorldScene scenario. The main code of HelloWorldScene. cpp is as follows:
Void HelloWorld: OnClickMenu1 (cocos2d: Ref * pSender) {NoteDAO: initDB (); NoteDAO: create ("10:01:02", "initialize data .");}


HelloWorld: OnClickMenu1 is the callback function when the player clicks the Init DB menu. In this function, the NoteDAO: initDB () statement is used to initialize the database. In NoteDAO, The initDB () function is a static function and can be called directly by instantiating NoteDAO. The following NoteDAO: create ("10:01:02", "initialize data.") statement is to call the create function in NoteDAO to insert a data entry in the Note table.


More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.cOcoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51wOrk6.com
Welcome to the Cocos2d-x Technology Discussion Group: 257760386 welcome to the knowledge of the iOS classroom public platform


Cocos2d-x using sqlite database, in win32 did not ask you, sqlite3_open under ios can not create a database, the returned value is 14

The db file path is incorrect.
Ios does not support file modification except the document directory

The use of cocos2d-x + VS to make small games, the use of sqlite, In the android transplant can not read the database

Sqlite3.c is used to operate sqlite. The download and use of this library are described in many tutorials.
On win32 and MacOS, this library is not used in particular, but on Android, it cannot be directly read.
The reason why Android cannot read databases is that database operations must have root permissions. That is to say, our applications can only operate database files in a specific directory provided by the system.
In this directory, cocos2.1.3 can be obtained through CCFileUtils: sharedFileUtils ()-> getWritablePath.
That is to say, we need to copy the sliqte library file under the Resource Directory to CCFileUtils: sharedFileUtils ()-> getWritablePath () to operate on it.
In this case, my solution is to implement the following in AppDelegate. cpp:
Bool isFileExist (const char * pFileName)
{
If (! PFileName) return false;
Std: string filePath = CCFileUtils: sharedFileUtils ()-> getWritablePath ();
FilePath + = pFileName;
FILE * pFp = fopen (filePath. c_str (), "r ");
CCLog (filePath. c_str ());
If (pFp)
{
Fclose (pFp );
Return true;
}
Return false;
}
Void copyData (const char * pFileName)
{
Std: string strPath = CCFileUtils: sharedFileUtils ()-> fullPathForFilename (pFileName );
Unsigned long len = 0;
Unsigned char * data = NULL;
Data = CCFileUtils: sharedFileUtils ()-> getFileData (strPath. c_str (), "r", & len );

Std: string destPath = CCFileUtils: sharedFileUtils ()-> getWritablePath ();
DestPath + = pFileName;

FILE * pFp = fopen (destPath. c_str (), "w + ");
Fwrite (data, sizeof (char), len, pFp );
Fclose (pFp );
Delete [] data;
Data = NULL;
}

Bool AppDelegate: applicationDidFinishLaunching ()
{
# If (CC_TARGET_PLATFORM! = CC_TARGET_WIN32) // copy the data file in Android
// Check whether the database file has been extracted
If (isFileExist ("dbd_user_save.db") = false)
{
CopyData ("dbd_user_save.db"); // The sqlite library file to be used
}

# Endif
// Lower

When the program starts, check whether sqlite exists and does not exist. Copy one copy.

Reposted from, and try again
... The remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.