iOS SQLite基础

SQLite Datatypes
SQLite uses five storage classes to represent all the
different types.
These types are: Null, Integer, Real, Text, Blob

  1. Creating a New Database
    Create a new database in code:

NSString * path = [filePathURL absoluteString];
sqlite3 * db;
const char * dbPath = [path UTF8String];
sqlite3_open(dbPath, &db);

  1. Create a new database in code in the command line and copy the database file into app bundle:

$ sqlite3 my_sqlite_db.sqlite

  1. Creating a New Table:

char * errorMessage;
const char * sql = "create table if not exists Tutorials (ID Integer Primary key AutoIncrement, Title Text, Author Text, PublicationDate Date);";
sqlite3_exec(db, sql, NULL, NULL, &errorMessage);

sqlite3_exec is convenience method for calling multiple statements of SQL without using lots of C code.
The NULL arguments are positions for callbacks (if necessary).

4.Inserting Data

sqlite3_stmt * statement;
const char * sql = "insert into Tutorials values (0, 'Intro to SQLite', 'Ray
Wenderlich', '2014-08-10 11:00:00')";
sqlite3_prepare_v2(db, sql, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"Inserted");
}
sqlite3_finalize(statement);

sqlite3_prepare_v2 - compiles the statement.
sqlite3_step - runs the statement. sqlite3_finalize - cleans up the memory.

5.Selecting Data

sqlite3_stmt * selectStatement;
const char * select_sql = "select * from Tutorials";
if (sqlite3_prepare_v2(db, select_sql, -1, &selectStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectStatement) == SQLITE_ROW)
{
int rowId = sqlite3_column_int(selectStatement, 0);
char * title = (char *) sqlite3_column_text(selectStatement, 1);
char * author = (char *) sqlite3_column_text(selectStatement, 2);
char * date = (char *) sqlite3_column_text(selectStatement, 3);
NSLog(@"%d %s %s %s",rowId,title,author,date);
}
}

6.Deleting and Updating

const char * update = "update Tutorials set Author = 'Brian Moakley' where ID = 0";
char * errorMessage;
if (sqlite3_exec(db, update, NULL, NULL, &errorMessage) != SQLITE_OK)
{
NSLog(@"Failed to update row");
}
const char * rmSql = "delete from Tutorials where ID = 0";
char * errorMessage;
if (sqlite3_exec(db, rmSql, NULL, NULL, &errorMessage) != SQLITE_OK)
{
NSLog(@"Failed to delete row");
}

demo:https://github.com/Joeyechang/MySqliteDemo2

你可能感兴趣的:(iOS SQLite基础)