SQLite数据库入门:掌握插入操作

发表时间: 2020-05-17 07:28


创建数据库和表

const char* createTableSQL =" CREATE TABLE TESTTABLE(int_col INT,float_col REAL ,string_col TEXT,ADDRESS char[50])";

2准备工作

char *zErrMsg = 0;int insertCount =10;const char* insertSQL = "INSERT INTO TESTTABLE(int_col,float_col,string_col,ADDRESS) VALUES(%d, %f, '%s', '%s');";const char* testString ="this is test.";const char* testAdd ="Is right?";char sql[1024];

(1)使用sqlite3_exec


for (int i = 0; i < insertCount; ++i){sprintf(sql, insertSQL, i, i*2.0, testString, testAdd);int rc = sqlite3_exec(conn, sql, 0, 0, &zErrMsg);if (rc != SQLITE_OK) {fprintf(stderr, "SQL error: %s\n", zErrMsg);sqlite3_free(zErrMsg);}else {fprintf(stdout, "Records created successfully\n");}}

(2)使用sqlite3_prepare_v2

sqlite3_stmt * stmt2 = NULL;for (int i = 20; i < insertCount+20; ++i){sprintf(sql, insertSQL, i, i*2.0, testString, testAdd);if (sqlite3_prepare_v2(conn, sql, strlen(sql), &stmt2, NULL) != SQLITE_OK){if (stmt2)sqlite3_finalize(stmt2);sqlite3_close(conn);return;}if (sqlite3_step(stmt2) != SQLITE_DONE){sqlite3_finalize(stmt2);sqlite3_close(conn);return;}printf("Insert Succeed.\n");}sqlite3_finalize(stmt2);