Cocos2d-x data persistence-query data, cocos2d-x Data Query

Source: Internet
Author: User

Cocos2d-x data persistence-query data, cocos2d-x Data Query
Data Query generally has query conditions, which can be implemented using the where clause of SQL statements. However, parameters must be dynamically bound to the where clause in the program. The procedure for querying data is as follows.
(1) Use the sqlite3_open function to open the database.
(2) Use the sqlite3_prepare_v2 function to pre-process SQL statements.
(3) Use the sqlite3_bind_text function to bind parameters.
(4) use the sqlite3_step function to execute an SQL statement and traverse the result set.
(5) use functions such as sqlite3_column_text to extract field data.
(6) use the sqlite3_finalize and sqlite3_close functions to release resources.


NoteDAO: findById in NoteDAO. cpp is a data query function based on the primary key. The related code is as follows:

ValueMap NoteDAO: findById (string pDate) {// initialize the database initDB (); sqlite3 * db = NULL; ValueMap dict; string path = dbDirectoryFile (); if (sqlite3_open (path. c_str (), & db )! = SQLITE_ OK) {① sqlite3_close (db); CCASSERT (false, "DB open failure.");} else {string qsql = "SELECT cdate, content FROM Note where cdate =? "; Sqlite3_stmt * statement; // pre-processing process if (sqlite3_prepare_v2 (db, qsql. c_str (),-1, & statement, NULL) = SQLITE_ OK) {② // start sqlite3_bind_text (statement, 1, pDate. c_str (),-1, NULL); ③ // execute if (sqlite3_step (statement) = SQLITE_ROW) {④ char * cdate = (char *) sqlite3_column_text (statement, 0); ⑤ char * content = (char *) sqlite3_column_text (statement, 1); dict ["date"] = Value (cdate ); dict ["content"] = Value (content) ;}} sqlite3_finalize (statement); ⑥ sqlite3_close (db); 7} return dict ;}


The function executes six steps. The step (1) is shown in line ① Of the code. It is the same as the first step for creating a database.
Step 2 is shown in line ② of the Code. The statement sqlite3_prepare_v2 (db, qsql. c_str (),-1, & statement, NULL) is a pre-processing SQL statement. The purpose of preprocessing is to compile SQL statements into binary code and improve the execution speed of SQL statements. The third parameter of the sqlite3_prepare_v2 function indicates the length of the SQL string, and-1 indicates all SQL strings. The fourth parameter is the address of the sqlite3_stmt pointer. It is a statement object that can be used to execute SQL statements. The fifth parameter is a part of the statements that are not executed by SQL statements.
Step 3 is shown in line ③ of the Code. The statement sqlite3_bind_text (statement, 1, pDate. c_str (),-1, NULL) is the parameter bound to an SQL statement. The first parameter is the statement pointer, and the second parameter is the serial number (starting from 1 ), the third parameter is the string value, the fourth parameter is the string length, and the fifth parameter is a function pointer. If an SQL statement contains a question mark, the question mark (which is a placeholder) is the parameter to be bound. The sample code is as follows:
String qsql = "SELECT cdate, content FROM Note where cdate =? ";
Step 4 is to use sqlite3_step (statement) to execute the SQL statement, as shown in line 4 of the Code. If the sqlite3_step function returns the int type (equal to SQLITE_ROW), it means that data in other rows is not traversed.
STEP (5) is to extract field data, as shown in row ⑤ Of the code. It uses the sqlite3_column_text (statement, 0) function to read string fields. Note that the second parameter of the sqlite3_column_text function is used to specify the index of the select field (starting from 0 ). The selection of the field function to be read is related to the field type. Similar common functions in SQLite3 include:
Sqlite3_column_blob ()
Sqlite3_column_double ()
Sqlite3_column_int ()
Sqlite3_column_int64 ()
Sqlite3_column_text ()
Sqlite3_column_text16 ()
For more information about other APIs, see http://www.sqlite.org/cintro.html.
Step 6 is to release resources, which is different from the database creation process. Before using the sqlite3_close function to close the database (see Row 7), you must use the sqlite3_finalize function to release the statement object statement, as shown in Row 6 of the Code.
NoteDAO: findAll () in NoteDAO. cpp is a function used to query all data. The related code is as follows:
ValueVector NoteDAO: findAll ()
{// Initialize the database initDB (); sqlite3 * db = NULL; string path = dbDirectoryFile (); ValueVector listData; if (sqlite3_open (path. c_str (), & db )! = SQLITE_ OK) {sqlite3_close (db); CCASSERT (false, "DB open failure. ");} else {string qsql =" SELECT cdate, content FROM Note "; sqlite3_stmt * statement; // pre-processing process if (sqlite3_prepare_v2 (db, qsql. c_str (),-1, & statement, NULL) = SQLITE_ OK) {// execute while (sqlite3_step (statement) = SQLITE_ROW) {char * cdate = (char *) sqlite3_column_text (statement, 0); char * content = (char *) sqlite3_column_text (statement, 1); ValueMap dict; dict ["date"] = Value (cdate ); dict ["content"] = Value (content); listData. push_back (Value (dict) ;}} sqlite3_finalize (statement); sqlite3_close (db) ;}return listData ;}

The query of all data functions is similar to the query of data functions based on the primary key. The difference is that the function does not have query conditions and does not need to bind parameters. When traversing, use the while LOOP statement, not the if statement:
while (sqlite3_step(statement) == SQLITE_ROW) {    ……}




To be able to call the findAll () function in NoteDAO, we need to call it in the HelloWorldScene scenario. The main code of HelloWorldScene. cpp is as follows:
void HelloWorld::OnClickMenu5(Ref* pSender){auto arry = NoteDAO::findAll();①for (auto& v: arry){log("-----------------");ValueMap row = v.asValueMap();②string date = row["date"].asString();③string content = row["content"].asString();④log("===>date: : %s", date.c_str());log("===>content: : %s", content.c_str());}}


HelloWorld: The OnClickMenu5 function is the callback function when the player clicks the Read Data menu. Line ① Of The Code calls the findAll () function in NoteDAO to query all functions. Line ② code converts the element v retrieved from the list to the ValueMap dictionary type. The Code in line ③ is to set the value of date from the dictionary. The fourth line of code is to take the content data from the dictionary.


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


What is data persistence?

1. What is persistence? I have found a lot of articles and have not found any satisfactory answers. I finally read the following explanation from "proficient in Hibernate: Java object persistence technology" written by Sun weiqin, I think it is complete. Excerpt: narrow understanding: "persistence" only refers to permanent storage of domain objects to the database. In a broad sense, "persistence" includes database-related operations. ● Save: Permanently Save the domain object to the database. ● Update: updates the status of domain objects in the database. ● Delete: delete a domain object from the database. ● Load: loads a domain object from the database to the memory based on a specific OID. ● Query: loads one or more domain objects that meet the query conditions from the database based on specific query conditions. 2. Why persistence? The persistence technology encapsulates data access details and provides object-oriented APIs for most business logic. ● Persistence technology can reduce the number of accesses to database data and increase the execution speed of applications; ● high code reusability, able to complete most database operations; ● loose coupling, the persistence does not depend on the underlying database and the upper-layer business logic. when changing the database, you only need to modify the configuration file instead of the Code.

What is data persistence?

Cmp and Hibernate are only different implementations of conversion between object models and relational models. However, object models and relational models are widely used. Therefore, we mistakenly believe that data persistence is the conversion from object models to relational databases.
The Hibernate framework provides this mechanism. The Hibernate framework synchronizes the modification to the database.
Data Persistence offers the following benefits:
1. Strong reusability of program code. Even if you change the database, you only need to change the configuration file without rewriting the program code.
2. the business logic code is highly readable, and there will be no large number of SQL languages in the code, improving the readability of the program.
3. The persistence technology can be automatically optimized to reduce access to the database and improve program running efficiency.
Data Persistence objects can be stored, updated, deleted, and queried.
Data Persistence mechanism in the Hibernate framework:
The Hibernate framework uses Session sessions between business programs and databases to submit, update, delete, and query data.
1. submit data to the database
2. query data from the database
Before querying data, you need to clear the cache (manually or automatically through the configuration file framework) to make the Session data consistent with the data in the database. Then the program only needs to query the data in the Session.
In short, data persistence is to solve the problem of interactive access between the program and the database, so that the program does not directly access the database, but directly access the Session, and then the Session will "deal" with the database ".

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.