How to create sqlite database programmatically?
SQLite isn’t the only way to persist data on iOS. Besides Core Data, there are lots of other alternatives for data persistence, including Realm, Couchbase Lite, Firebase, and NSCoding.
SQLite does have some advantages:
- Shipped with iOS so it adds no overhead to your app’s bundle
- Tried and tested; version 1.0 was released in August 2000
- Open source
- Familiar query language for database developers and admins
- Cross-platform
Creating a Table
Now that you have a connection to a database file, you can create a table. You’ll work with a very simple table to store contacts.
// SWIFT
func createTable() {
// 1
var createTableStatement: OpaquePointer? = nil
// 2
if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {
// 3
if sqlite3_step(createTableStatement) == SQLITE_DONE {
print("Contact table created.")
} else {
print("Contact table could not be created.")
}
} else {
print("CREATE TABLE statement could not be prepared.")
}
// 4
sqlite3_finalize(createTableStatement)
}
// OBJECTIVE-C
-(void)createDatabase
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"timings.db"]];
if ([[NSFileManager defaultManager] fileExistsAtPath:databasePath] == FALSE)
{
if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK)
{
const char *sqlStatement = "CREATE TABLE IF NOT EXISTS TIMINGS (ID INTEGER PRIMARY KEY AUTOINCREMENT, TIMESTAMP TEXT, TIMING TEXT)";
char *error;
sqlite3_exec(timingsDatabase, sqlStatement, NULL, NULL, &error);
sqlite3_close(timingsDatabase);
}
}
}
-(void)storeTiming
{
if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK)
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO TIMINGS (TIMESTAMP, TIMING) VALUES (\"%@\", \"%@\")", [dateFormatter stringFromDate:startDate], stopWatchLabel.text];
char *error;
sqlite3_exec(timingsDatabase, [insertStatement UTF8String], NULL, NULL, &error);
sqlite3_close(timingsDatabase);
}
}
-(void)getTimings
{
if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK)
{
NSString *queryStatement = [NSString stringWithFormat:@"SELECT TIMESTAMP, TIMING FROM TIMINGS"];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(timingsDatabase, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW) {
NSLog(@"Timestamp: %s Timing: %s", sqlite3_column_text(statement, 0), sqlite3_column_text(statement, 1));
}
sqlite3_finalize(statement);
sqlite3_close(timingsDatabase);
}
}
}
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.