Basic operations for adding, deleting, modifying, and querying the FMDN database of the iOS Database
FMDB (https://github.com/ccgus/fmdb) is not much to say first to add this library, in will be added, OK preparation work ready code.
# Import "DDViewController. h"
# Import "FMDB. h"
@ Interface DDViewController ()
{
FMDatabase * db;
}
@ End
@ Implementation DDViewController
/**
* First, you must have a location to store the Document path of the database under ios. Document is a folder that can be read and written in ios and you must create a database list.
*/
-(Void) viewDidLoad
{
[SuperviewDidLoad];
// Db = [FMDatabase new];
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentDirectory = [paths objectAtIndex: 0];
// DbPath: Specifies the database path in Document.
NSString * dbPath = [documentDirectory stringByAppendingPathComponent: @ "Test. db"];
// Create a database instance db. If the "Test. db" file does not exist in the path, sqlite automatically creates "Test. db"
Db = [FMDatabasedatabaseWithPath: dbPath];
If (! [Db open]) {
NSLog (@ "cocould not open db .");
Return;
}
// Set cache for the database to improve query efficiency
[DbsetShouldCacheStatements: YES];
// 1. Create a table named "User"
[SelfcreatTable];
// 2. Add data to the table
[SelfinsertData: @ "Straw hat" age: 23];
// 3. view the result
[SelfResultSet];
}
// Create a table
-(Void) creatTable
{
// When creating a table, it is best to determine whether your previous work is well performed.
If (! Db ){
NSLog (@ "database does not exist ");
}
If (! [Db open]) {
[Dbopen];
}
// Determine whether the table named "User" exists. If no table is created
If (! [Db tableExists: @ "User"]) {
// Create a table named User with two fields: string-type Name and integer-type Age.
[DbexecuteUpdate: @ "create table User (Name text, Age integer)"];
// [Self insertData: @ "Straw hat" age: 24];
}
}
// Insert data
-(Void) insertData :( NSString *) name age :( int) age
{
// Insert data using the type text in OC corresponding to NSString integer corresponding to int integer
[DbexecuteUpdate: @ "insert into User (Name, Age) VALUES (?,?) ", Name, [NSNumbernumberWithInt: age];
}
// Query results
-(Void) ResultSet
{
// Return the first matching result in the database
NSString * aa = [dbstringForQuery: @ "SELECT Name FROM User WHERE Age =? ", @" 20 "];
NSLog (@ "aa is % @", aa );
FMResultSet * rs = [dbexecuteQuery: @ "SELECT * FROM User"];
// Rs = [db executeQuery: @ "SELECT * FROM User WHERE Age =? ", @" 23 "];
While ([rs next]) {
NSLog (@ "% @", [rsstringForColumn: @ "Name"], [rsstringForColumn: @ "Age"]);
}
[Rsclose];
}
// Modify Table content
-(Void) Modify
{
[DbexecuteUpdate: @ "UPDATE User SET Name =? WHERE Name =? ", @" Li Si ", @" Zhang San "];
}
-(Void) didReceiveMemoryWarning
{
[SuperdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@ End