iOS SQLite operation method

  • 2020-06-03 08:31:05
  • OfStack

Today is finally used to spend a little bit of time before the project of SQLite operation method under 1 and uploaded to the github, download address: (https: / / github com/peanutNote/QYSQLiteManagerDemo git).

The main purpose is to simplify the operation of SQLite in the code. Specific usage:

Add the QYSQLiteManager file add to your project and add #import "QYSQLiteManager" to the class that needs to operate on SQLite.


//  Insert statement 
- (void)insertTable
{
 //  create sql statements 
 NSString *sql = @"insert into teacher(name,id) values(?,?)";
 //  Immutable parameter 
// BOOL isOK = [QYSQLiteManager insertTableWithSqlString:sql andArray:@[@" Xiao Ming ",@115]];
 //  Variable parameter 
 BOOL isOK = [QYSQLiteManager insertTableWithSqlString:sql andObjects:@" Xiao Ming ",@"115", nil];
 if (isOK) {
  NSLog(@" Data insertion successful ");
 } else {
  NSLog(@" Data insertion failure ");
 }
}
//  The query 
- (void)selectTable
{
 NSString *sql = @"select * from teacher";
 [QYSQLiteManager selectTableWithSqlString:sql didFinishedBlock:^(NSArray *dataList, NSString *error) {
  NSLog(@"%@",dataList);
 } andObjects:nil];
}

//  Modify the sentence 
- (void)alterTable
{
 NSString *sql = @"alter table teacher add column pwd integer";
 if([QYSQLiteManager alterTableWithSqlString:sql])
 {
  NSLog(@" Modify the success ");
 }
}

//  Update data statement 
- (void)updateTable
{
 NSString *sql = @"update teacher set name = ? where id = ?";
 if ([QYSQLiteManager updateTableWithSqlString:sql andArray:@[@" Xiao Ming ",@115]]) {
  NSLog(@" The update is successful ");
 }
}

As for the data type returned by the query statement, students who need it can find "sqlite3_bind_text" in "QYSQLiteManager.m" by themselves, and then find it below


for (int i = 0; i < column_count; i++) {
     //  Get the field name 
     char * keyName = (char *)sqlite3_column_name(stmt, i);
     NSString *key = [NSString stringWithUTF8String:keyName];
     if (sqlite3_column_type(stmt, i) == SQLITE_TEXT) { //  When the field data is" text " 
      //  Gets the data corresponding to the field 
      char *valueName = (char *)sqlite3_column_text(stmt, i);
      NSString *value = [NSString stringWithUTF8String:valueName];
      [dataDic setObject:value forKey:key];
     } else { //  When field data is integer when 
      int value = sqlite3_column_int(stmt, i);
      [dataDic setObject:@(value) forKey:key];
     }
    }

Just change the type of data you want.

Above content is this site to you daily collection of iOS sqlite database operations, hope to help you


Related articles: