适合嵌入式linux方面的数据库SQLite3
SQLite3是一个开源的嵌入式数据库引擎,它实现了多数的SQL92标准,并且只占用很少的资源。它通过API进行访问,并且在许多嵌入式产品中使用。
以下是一些SQLite3在嵌入式Linux项目中的应用:
- 创建/打开数据库:
#include <sqlite3.h>
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
sqlite3_close(db);
return 0;
}
- 执行SQL命令:
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
for(int i = 0; i < argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
sql = "CREATE TABLE COMPANY(" \
"ID INTEGER PRIMARY KEY AUTOINCREMENT," \
"NAME TEXT NOT NULL," \
"AGE INTEGER NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL );";
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
- 使用参数化查询:
#include <sqlite3.h>
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
sqlite3_stmt *res;
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
sql = "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) " \
"VALUES (?, ?, ?, ?, ?);";
rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
if( rc != SQLITE_OK ){
fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return 0;
}
sqlite3_bind_int(res,
评论已关闭