Basic use of iOS Databases
Summary of the basic usage of the database today:
The database used by iOS is generally sqlite3. before using the database, you must first import the database framework. Otherwise, an error occurs. Next, introduce the header file # import <sqlite3.h>
Create a Model class Student and a database tool class DataBaseTool in the project
Define several attributes in Student. h:
# Import <Foundation/Foundation. h>
@ Interface Student: NSObject
@ Property (nonatomic, copy) NSString * name;
@ Property (nonatomic, copy) NSString * holobby;
@ Property (nonatomic, assign) NSInteger age;
@ End
Database Operation Method declaration in DataBaseTool. h:
# Import <Foundation/Foundation. h>
# Import <sqlite3.h>
# Import "Student. h"
@ Interface DataBaseTool: NSObject
{
// Address used to save the database object
Sqlite3 * dbPoint;
}
// To ensure that the current database is unique in the project, we create a database tool object using a single instance.
+ (DataBaseTool *) define dataBaseTool;
// Open the database
-(Void) openDB;
// Create a table for the database.
-(Void) createTable;
// Insert a student information
-(Void) insertStu :( Student *) stu;
// Update the student information
-(Void) updateStu :( Student *) stu;
// Delete operation
-(Void) deletedateStu :( Student *) stu;
// Query operation
-(NSMutableArray *) selectAllStu;
// Close the database
-(Void) closeDB;
@ End
Implementation Method in DataBaseTool. m:
# Import "dataBaseTool. h"
@ Implementation dataBaseTool
+ (DataBaseTool *) specify dataBaseTool {
Static dataBaseTool * tool;
Static dispatch_once_t oneToken;
Dispatch_once (& oneToken, ^ {
Tool = [[dataBaseTool alloc] init];
});
Return tool;
}
-(Void) openDB {
// The database file is also saved in the hosts file of the sandbox, so first find the sandbox path
NSArray * sandBox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * sandBoxPath = sandBox [0];
// Concatenate the file path. If the system finds the corresponding file based on the file path, it will open the database directly. If not, a corresponding database will be created.
NSString * documentPath = [sandBoxPath stringByAppendingPathComponent: @ "Student. sqlite"];
Int result = sqlite3_open ([documentPath UTF8String], & dbPoint );
If (result = SQLITE_ OK ){
NSLog (@ "database opened successfully ");
NSLog (@ "% @", documentPath );
} Else {
NSLog (@ "database opening failed ");
}
}
-(Void) createTable {
// Primary key indicates the primary key. The primary key is unique in the current table and cannot be duplicated. It can uniquely identify a data record, usually an integer.
// Autoincrement auto-increment. In order to keep the primary key unique, the primary key will be auto-incrementing.
// If not exists is created only if no table exists, preventing duplicate creation and overwriting of previous data
// Database problem 90% is an SQL statement problem. Therefore, ensure that the statement is correct and then use it in the project.
NSString * sqlStr = @ "create table if not exists stu (number integer primary key autoincrement, name text, age integer, Hober text )";
// Execute this SQL statement
Int result = sqlite3_exec (dbPoint, [sqlStr UTF8String], nil );
If (result = SQLITE_ OK ){
NSLog (@ "table created successfully ");
} Else {
NSLog (@ "Table creation failed ");
}
}
-(Void) insertStu :( Student *) stu {
NSString * sqlStr = [NSString stringWithFormat: @ "insert into stu (name, age, Hober) values ('% @', '% ld', '% @')", stu. name, stu. age, stu. holobby
];
// Execute the SQL statement
Int result = sqlite3_exec (dbPoint, [sqlStr UTF8String], nil );
If (result = SQLITE_ OK ){
NSLog (@ "student added ");
} Else {
NSLog (@ "failed to add student ");
}
}
-(Void) updateStu :( Student *) stu {
NSString * sqlStr = [NSString stringWithFormat: @ "update stu set Hoby = '% @', age = % ld where name = '% @'", stu. holobby, stu. age, stu. name];
// Execute the SQL statement
Int result = sqlite3_exec (dbPoint, [sqlStr UTF8String], nil );
If (result = SQLITE_ OK ){
NSLog (@ "updated successfully ");
} Else {
NSLog (@ "update failed ");
NSLog (@ "% d", result );
}
}
-(Void) deletedateStu :( Student *) stu {
NSString * sqlStr = [NSString stringWithFormat: @ "delete from stu where name = '% @'", stu. name];
// Execute the SQL statement
Int result = sqlite3_exec (dbPoint, [sqlStr UTF8String], nil );
If (result = SQLITE_ OK ){
NSLog (@ "deleted successfully ");
} Else {
NSLog (@ "deletion failed ");
}
}
-(NSMutableArray *) selectAllStu {
// Query Logic
// 1. Read all data in a table from the local database first
// 2. Read the data one by one and assign values to the model.
// 3. Put the model that has been assigned a good value into the array and return
NSString * sqlStr = @ "select * from stu ";
// In the statement, * Indicates a wildcard. A * is used to replace all the field names in the table.
// Next we need to define a following pointer to traverse each row of data in the database table.
// The third parameter is the limit on the number of words in the query statement.-1 indicates no limit.
Sqlite3_stmt * stmt = nil;
Int result = sqlite3_prepare_v2 (dbPoint, [sqlStr UTF8String],-1, & stmt, nil );
// This method is equivalent to associating the database with the following pointer to complete the query function.
// Initialize an array for loading students
NSMutableArray * stuArr = [NSMutableArray array];
If (result = SQLITE_ OK ){
NSLog (@ "query successful ");
// Start traversing and querying each row of data in the database
While (sqlite3_step (stmt) = SQLITE_ROW ){
// Let the following pointer traverse the query. If there are no rows, the loop will be stopped.
// If the conditions are met, the content is read one by one
// The second parameter indicates the number of data columns in the current table.
Const unsigned char * name = sqlite3_column_text (stmt, 1 );
Int age = sqlite3_column_int (stmt, 2 );
Const unsigned char * holobby = sqlite3_column_text (stmt, 3 );
// Convert the data in the column type again
NSInteger stuAge = age;
NSString * stuName = [NSString stringwithuf8string :( const char *) name];
NSString * stuholobby = [NSString stringwithuf8string :( const char *) holobby];
// Assign a value to the object and put the object in the array
Student * stu = [[Student alloc] init];
Stu. name = stuName;
Stu. holobby = stuholobby;
Stu. age = stuAge;
[StuArr addObject: stu];
[Stu release];
}
} Else {
NSLog (@ "query failed ");
NSLog (@ "% d", result );
}
Return stuArr;
}
-(Void) closeDB {
Int result = sqlite3_close (dbPoint );
If (result = SQLITE_ OK ){
NSLog (@ "database closed successfully ");
// NSLog (@ "% @", documentPath );
} Else {
NSLog (@ "database shutdown failed ");
}
}
@ End