IOS Development Database (SQLite)

Source: Internet
Author: User

IOS Development Database (SQLite)
Advantages of SQLite embedded database:
1. Embedded Database
2. Support events, no configuration, no installation, no administrator
3. Supports most SQL92 standards
4. The complete database is stored in a file on the disk. The same database file can be used on different machines. The maximum size of the database is 2 TB.
5. The entire system contains less than 30 thousand rows, and less than KB of memory is occupied.

Start using SQLite:
1. Introduce the header file
2. Open the database
3. Execute SQL commands
4. Shut down the database

The following code enables, disables, adds, deletes, searches, and modifies the entire database.

Create a ticket:

 

# Import
 
  
@ Class Student; @ interface DataBaseHandle: NSObject // create a single instance + (DataBaseHandle *) shareDB; // obtain the Documents path-(NSString *) documentsPath; // Open Database-(void) openDB; // close database-(void) closeDB; // create table-(void) createTable; // insert information-(void) insertStudent :( Student *) stu; // modify information-(void) updateMessage; // delete information-(void) deleteMessage; // find all-(void) selectAllStudent; // conditional search (example)-(void) selectWithSex :( NSString *) sex; @ end
 

# Import DataBaseHandle. h # import
 
  
# Import Student. h // global single-profit object static DataBaseHandle * inclumodle = nil; @ implementation DataBaseHandle # pragma mark realize Single-Profit + (DataBaseHandle *) shareDB {if (nil = inclumodle) {export modle = [[DataBaseHandle alloc] init];} return export modle;} # pragma mark obtains the Documents path-(NSString *) documentsPath {NSString * documentPath = paths (NSDocumentDirectory, NSUserDomainMask, YES) [0]; retur N documentPath;} // introduce the framework (SQL... 3.0) // declare a database object static sqlite3 * db = nil; # pragma mark open the database-(void) openDB {// determine whether the database is empty if (nil = db) {// concatenate the database storage path with the documents path (obtain the storage path) NSString * dbPath = [[self documentsPath] stringByAppendingString: @/Student. sqlite]; // open the database according to the path. If there is no database under the path, a database is automatically created. // open the database (the syntax in the C language) int result = sqlite3_open (dbPath. UTF8String, & db); // determines whether the database is successfully opened if (result = SQLITE_ OK ){ NSLog (@ database opened successfully);} else {NSLog (@ database opened failed); }}# pragma mark closes the database-(void) closeDB {int result = sqlite3_close (db); if (result = SQLITE_ OK) {// if it is disabled successfully, set it to nill db = nil; NSLog (@ database closed successfully );} else {NSLog (@ database shutdown failed) ;}# pragma mark creates a table-(void) createTable {// to create a table, use an SQL statement. // The NSString * createString = @ create table if not exists student (sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Sname TEXT, ssex TEXT, sage TEXT); // execute the SQL statement int result = sqlite3_exec (db, createString. UTF8String, NULL); if (result = SQLITE_ OK) {NSLog (@ table created successfully);} else {NSLog (@ creation failed );}} # pragma mark INSERT information-(void) insertStudent :( Student *) stu {// prepare the INSERT statement NSString * insertString = [NSString stringWithFormat: @ insert into student (sname, ssex, sage) VALUES ('% @', '% @', '% @'), stu. name, stu. sex, stu. age]; // run Statement int result = sqlite3_exec (db, insertString. UTF8String, NULL); if (result = SQLITE_ OK) {NSLog (@ inserted successfully);} else {NSLog (@ inserted failed );}} # pragma mark modify data-(void) updateMessage {// prepare the modification statement NSString * undataString = @ UPDATE student SET ssex = 'female ', sname = 'shumeng' WHERE sid = 10; int result = sqlite3_exec (db, undataString. UTF8String, NULL); if (result = SQLITE_ OK) {NSLog (@ modified successfully);} else {NSLog (@ modification failed) ;}# pragma mark deletes data-(void) deleteMessage {// prepare the deletion statement NSString * deleteString = @ delete from student WHERE sid = 1; int result = sqlite3_exec (db, deleteString. UTF8String, NULL); if (result = SQLITE_ OK) {NSLog (@ delete OK);} else {NSLog (@ delete _ NO );}} # pragma mark search all-(void) selectAllStudent {// prepare the search statement NSString * selectAll = @ SELECT * FROM student; // create the accompanied pointer sqlite3_stm T * stmt = nil; // The int result = sqlite3_prepare (db, selectAll. UTF8String,-1, & stmt, NULL); if (result = SQLITE_ OK) {// The while (sqlite3_step (stmt) = SQLITE_ROW) is executed cyclically until the query is complete) {// retrieve sid (column 0th) NSInteger sid = sqlite3_column_int (stmt, 0); // retrieve sname (column 1st) NSString * sname = [NSString stringwithuf8string :( const char *) sqlite3_column_text (stmt, 1)]; // retrieves the ssex (2nd columns) NSString * ssex = [NSString stringWit Huf8string :( const char *) sqlite3_column_text (stmt, 2)]; // retrieve sage (column 3rd) NSString * sage = [NSString stringwithuf8string :( const char *) sqlite3_column_text (stmt, 3)]; NSLog (@ sid: % d sname: % @ ssex: % @ sage: % @, sid, sname, ssex, sage);} sqlite3_finalize (stmt );} else {// if the search fails, end with the pointer sqlite3_finalize (stmt); NSLog (@ search failed) ;}# pragma mark condition search-(void) selectWithSex :( NSString *) sex {// prepare the search statement NSString * selecstS Tring = @ SELECT * FROM student WHERE ssex = ?; // Create the companion pointer sqlite3_stmt * stmt = nil; // pre-Execute int result = sqlite3_prepare (db, selecstString. UTF8String,-1, & stmt, NULL); if (result = SQLITE_ OK) {// bind? The value of // 1 represents the first question mark? Which parameter is bound to sqlite3_bind_text (stmt, 1, sex. UTF8String,-1, NULL); while (sqlite3_step (stmt) = SQLITE_ROW) {NSInteger sid = sqlite3_column_int (stmt, 0 ); NSString * sname = [NSString stringwithuf8string :( const char *) sqlite3_column_text (stmt, 1)]; NSString * ssex = [NSString stringwithuf8string :( const char *) substring (stmt, 2)]; NSString * sage = [NSString stringwithuf8string :( const char *) sqlite3_column_text (stmt, 3)]; NSLog (@ sid: % d sname: % @ ssex: % @ sage: % @, sid, sname, ssex, sage) ;}} else {// close the pointer sqlite3_finalize (stmt); NSLog (@ query failed); }}@ end
 

 

Create a Student class
#import 
 
   @interface Student : NSObject@property(nonatomic,strong)NSString *name;@property(nonatomic,strong)NSString *age;@property(nonatomic,strong)NSString *sex;@end
 
Call ViewDidLoad in ViewController. m
// Print the path NSLog (% @, [[DataBaseHandle shareDB] documentsPath]); // open the database [[DataBaseHandle shareDB] openDB]; // create a table [[DataBaseHandle shareDB] createTable]; // insert information // Student * stu = [[Student alloc] init]; // stu. name = @ Xiaolu; // stu. age = @ 29; // stu. sex = @; // [[DataBaseHandle shareDB] insertStudent: stu]; // modify // [[DataBaseHandle shareDB] updateMessage]; // Delete // [[DataBaseHandle shareDB] deleteMessage]; // query all information // [[DataBaseHandle shareDB] selectAllStudent]; // search for information based on the condition [[DataBaseHandle shareDB] selectWithSex: @ ];

 

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.