「iOS開発」iosでSQLiteの基本的なデータベース操作

1.ライブラリをインポート
#import “/usr/include/sqlite3.h"

2.データベースを開く
int sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);

3.テーブルの操作
int sqlite3_exec(
sqlite3*, /* An open database */
const char *sql, /* SQL to be evaluated */
int (*callback)(void*,int,char**,char**), /*Callbk func*/
void *, /* 1st argument to callback*/
char **errmsg /* Error msg written here */
);

4.SQLiteの5つデータ種類:
INTEGER、 TEXT、BLOB、NULL、REAL

5.サンプルコード:
#import “/usr/include/sqlite3.h"
int main(int argc, char *argv[]) {
char *sqlStatement;
sqlite3 *pDb;
char *errorMsg;
int returnCode;
char *databaseName;
databaseName = “financial.db";
returnCode = sqlite3_open(databaseName, &pDb);
if(returnCode!=SQLITE_OK) {
fprintf(stderr, “Error in opening the database. Error: %s",
sqlite3_errmsg(pDb));
sqlite3_close(pDb);
return -1;
}
sqlStatement = “DROP TABLE IF EXISTS stocks";
returnCode = sqlite3_exec(pDb, sqlStatement, NULL, NULL, &errorMsg);
if(returnCode!=SQLITE_OK) {
fprintf(stderr,
“Error in dropping table stocks. Error: %s", errorMsg);
sqlite3_free(errorMsg);
}
sqlStatement = “CREATE TABLE stocks (symbol VARCHAR(5), "
“purchasePrice FLOAT(10,4), "
“unitsPurchased INTEGER, "
“purchase_date VARCHAR(10))";
returnCode = sqlite3_exec(pDb, sqlStatement, NULL, NULL, &errorMsg);
if(returnCode!=SQLITE_OK) {
fprintf(stderr, “Error in creating the stocks table. Error: %s",
errorMsg);
sqlite3_free(errorMsg);
}
insertStockPurchase(pDb, “ALU", 14.23, 100, “03-17-2012");
insertStockPurchase(pDb, “GOOG", 600.77, 20, “01-09-2012");
insertStockPurchase(pDb, “NT", 20.23,140, “02-05-2012");
insertStockPurchase(pDb, “MSFT", 30.23, 5, “01-03-2012");
sqlite3_close(pDb);
return 0;
}

void insertStockPurchase(sqlite3 *pDb, const char*symbol,
float price, int units, const char* theDate){
char *errorMsg;
int returnCode;
char *st;
st = sqlite3_mprintf(“INSERT INTO stocks VALUES"
" (’%q’, %f, %d, ’%q’)", symbol, price, units, theDate);
returnCode = sqlite3_exec(pDb, st, NULL, NULL, &errorMsg);
if(returnCode!=SQLITE_OK) {
fprintf(stderr,
“Error in inserting into the stocks table. Error: %s",
errorMsg);
sqlite3_free(errorMsg);
}
sqlite3_free(st);
}

IOS

Posted by arkgame