C语言中 sqlite3 的 一些调用方式

前端之家收集整理的这篇文章主要介绍了C语言中 sqlite3 的 一些调用方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


1.创建数据库


2.创建表



3.清空表中数据



4.插入数据

/****************insert data prepare********************/
sqlite3_stmt* stmt1 = NULL;
const char* beginsql = "BEGIN TRANSACTION";
if (sqlite3_prepare_v2(conn,beginsql,strlen(beginsql),&stmt1,NULL) !=sqlITE_OK)
{
if (stmt1)
sqlite3_finalize(stmt1);
sqlite3_close(conn);
return;
}


if (sqlite3_step(stmt1) != sqlITE_DONE) {
sqlite3_finalize(stmt1);
sqlite3_close(conn);
return;
}
sqlite3_finalize(stmt1);
/******************bind and insert****************************/
const char* insertsql = "INSERT INTO basicpower VALUES(?,?)";
sqlite3_stmt* stmt3 = NULL;
if (sqlite3_prepare_v2(conn,insertsql,strlen(insertsql),&stmt3,NULL) != sqlITE_OK) {
if (stmt3)
sqlite3_finalize(stmt3);
sqlite3_close(conn);
return;
}
//char a[2000];
for(i=0;i<len;i++)
{
sqlite3_bind_int(stmt3,1,i);
sqlite3_bind_int(stmt3,2,data[i]);
//将数组中的数据绑定,然后插入表中

if (sqlite3_step(stmt3) != sqlITE_DONE) {
sqlite3_finalize(stmt3);
sqlite3_close(conn);
return;
}
/*****重新初始化该sqlite3_stmt对象绑定的变量。***/
sqlite3_reset(stmt3);
printf("Insert Succeed.\n");


}
sqlite3_finalize(stmt3);
/********提交之前的事物。********/
const char* commitsql = "COMMIT";
sqlite3_stmt* stmt4 = NULL;
if (sqlite3_prepare_v2(conn,commitsql,strlen(commitsql),&stmt4,NULL) !=sqlITE_OK) {
if (stmt4)
sqlite3_finalize(stmt4);
sqlite3_close(conn);
return;
}
if (sqlite3_step(stmt4) != sqlITE_DONE) {
sqlite3_finalize(stmt4);
sqlite3_close(conn);
return;
}
printf("finish insert data ok\n");
sqlite3_finalize(stmt4);



5.取出数据

const char* selectsql = "SELECT data FROM basicpower"; //直接选择要查询的数据列 sqlite3_stmt* stmt3 = NULL; if (sqlite3_prepare_v2(conn,selectsql,strlen(selectsql),NULL) !=sqlITE_OK) { if (stmt3) sqlite3_finalize(stmt3); sqlite3_close(conn); return; } int count=0; int fieldCount = sqlite3_column_count(stmt3); //有几个要查询的列。这里就一个data数据列 printf("the count is %d \n",fieldCount); do{ int i; int r = sqlite3_step(stmt3); if (r == sqlITE_ROW) { for (i = 0; i < fieldCount; ++i) { int vtype = sqlite3_column_type(stmt3,i); if (vtype == sqlITE_INTEGER) { int v = sqlite3_column_int(stmt3,i); //printf("The INTEGER value is %d.\n",v); data[count]=v; //将取出的数据放入要发送的数组中后面的判断是对其他类型的。 } else if (vtype == sqlITE_FLOAT) { double v = sqlite3_column_double(stmt3,i); printf("The DOUBLE value is %f.\n",v); } else if (vtype == sqlITE_TEXT) { const char* v = (const char*)sqlite3_column_text(stmt3,i); printf("The TEXT value is %s.\n",v); } else if (vtype == sqlITE_NULL) { printf("This value is NULL.\n"); } } }else if (r == sqlITE_DONE) { printf("Select Finished.\n"); break; } else { printf("Failed to SELECT.\n"); sqlite3_finalize(stmt3); sqlite3_close(conn); return; } count++; //循环将取出的值放入data[count]数组中 }while(1); sqlite3_finalize(stmt3); break;

猜你在找的Sqlite相关文章