The results of the program run as follows:
Enter name and age, and click the "Confirm Insert" button to insert a record into the database.
The program code is as follows: (with detailed comments, I believe everyone can understand Kazakhstan!!!)
//
Viewcontroller.m
Basic operation of SQLite
//
Created by Mac1 on 15/10/6.
Copyright (c) 2015 www.iphonetrain.com. All rights reserved.
//
#import "ViewController.h"
Import library files
#import <sqlite3.h>
@interface Viewcontroller ()
Name
@property (Weak, nonatomic) Iboutlet Uitextfield *nametextfield;
Age
@property (Weak, nonatomic) Iboutlet Uitextfield *agetextfield;
@property (nonatomic,assign) sqlite3 *db; global variable defaults to NULL
"Confirm Insert" button
-(ibaction) insertaction;
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
The path to the build database
NSString *dbfilepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "documents/test.db"];
Print Database save path
NSLog (@ "Dbfilepath =%@", Dbfilepath);
1. Create the database, and if there is no database, create
_db = NULL;
int status = Sqlite3_open (dbfilepath.utf8string, &_db);
if (status = = Sqlite_ok) {
NSLog (@ "Open database successfully!");
2. Create a table
char *errmsg = NULL;
Sqlite3_exec (_db, "CREATE TABLE IF not EXISTS t_user (ID integer PRIMARY KEY, Name text, age integer)", NULL, NULL, &E RRMSG);
if (errmsg) {
NSLog (@ "Failed to create TABLE!");
}
}
Querying data
[Self querydata];
}
"Confirm Insert" button is clicked
-(ibaction) insertaction {
DML Insert
NSString *insertsql = [NSString stringwithformat:@ "INSERT into T_user (name,age) VALUES ('%@ ', '%ld ') ', _ Nametextfield.text,[_agetextfield.text IntegerValue]];
Inserting data
char *error = NULL;
Sqlite3_exec (_db, insertsql.utf8string, NULL, NULL, &ERROR);
if (Error) {
NSLog (@ "Insert record failed!");
}
}
DQL use of query statements
-(void) querydata{
Prepare the query (check the legality of the SQL statement)
Parameter value-1 indicates the internal calculation size of the program
sqlite3_stmt *stmt = NULL;
int status = SQLITE3_PREPARE_V2 (_db, "select * from T_user",-1, &stmt, NULL);
Indicates that there is data
if (status = = Sqlite_ok) {
Sqlite3_step (stmt) = = Sqlite_row The data that the current stmt points to has a value
while (Sqlite3_step (stmt) = = Sqlite_row) {
Take out the value in the Name field in one piece of data
Const unsigned char *name = Sqlite3_column_text (stmt, 1);
Take out the value in the age field in one piece of data
int age = Sqlite3_column_int (stmt, 2);
NSLog (@ "name =%s, age =%d", name,age);
}
}
}
@end
However, the operation of the database, generally using the third-party framework FMDB operation
: Https://github.com/ccgus/fmdb
Simple use of SQLite