首页 > 代码库 > sqlite学习笔记9:C语言中使用sqlite之插入数据
sqlite学习笔记9:C语言中使用sqlite之插入数据
前面创建了一张表,现在给他插入一些数据,插入数据跟创建表差不多,仅仅是SQL语言不一样而已,完整代码如下:
#include <stdio.h> #include <stdlib.h> #include "sqlite/sqlite3.h" #define DB_NANE "sqlite/test.db" sqlite3 *db = NULL; char* sql = NULL; char *zErrMsg = NULL; int ret = 0; typedef enum{ false, true } bool; /* typedef int (*sqlite3_callback)( void*, Data provided in the 4th argument of sqlite3_exec() int, The number of columns in row char**, An array of strings representing fields in the row char** An array of strings representing column names ); */ static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i = 0; for(i=0; i < argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } bool connectDB() { ret = sqlite3_open(DB_NANE, &db); if( ret != SQLITE_OK){ fprintf(stderr, "Error open database: %s\n", sqlite3_errmsg(db)); sqlite3_free(zErrMsg); return false; } fprintf(stdout, "Successfully opened database\n"); return true; } bool createTable() { /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" "ID INT PRIMARY KEY NOT NULL," "NAME TEXT NOT NULL," "AGE INT NOT NULL," "ADDRESS CHAR(50)," "SALARY REAL );"; /* Execute SQL statement */ ret = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( ret != SQLITE_OK ){ fprintf(stderr, "Error SQL: %s\n", zErrMsg); sqlite3_free(zErrMsg); return false; } fprintf(stdout, "Successfully table created\n"); return true; }
/*添加了此函数*/ bool insertRecords() { /* Create SQL statement */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */ ret = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( ret != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); return false; } fprintf(stdout, "successfully records created\n"); return true; }
bool closeDB() { int ret = 0; ret = sqlite3_close(db); if ( ret == SQLITE_BUSY ){ return false; } return true; } int main(int argc, char* argv[]) { connectDB(); /*createTable();*/ insertRecords(); closeDB(); return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。