以下是通过 sqlite3_prepare_v2/sqlite3_bind_text 绑定数据库,向数据库 写入 user1, pass1// create by cnfreebsd@163.com #include "sqlite3.h" #include <stdio.h> #include <stdlib.h> #include <string.h> int main( int argc, char **argv ) { char *file = "database.db"; sqlite3 *db = NULL; int rc = 0; sqlite3_stmt *stmt = NULL; sqlite3_initialize( ); rc = sqlite3_open_v2( file, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL ); if ( rc != SQLITE_OK) { sqlite3_close( db ); exit( -1 ); } const char create_tables_sql[] = "CREATE TABLE IF NOT EXISTS users (" "username TEXT PRIMARY KEY NOT NULL," "password TEXT NOT NULL);"; if (sqlite3_exec(db, create_tables_sql, NULL, NULL, NULL) != SQLITE_OK) { sqlite3_finalize(stmt); printf("Failed to create tables"); exit( -1 ); } const char insert_user_sql[] = "INSERT INTO users VALUES(" ":username," ":password);"; if (sqlite3_prepare_v2(db, insert_user_sql, -1, &stmt, NULL) != SQLITE_OK) { printf("Failed to prepare statement"); sqlite3_finalize(stmt); exit( -1 ); } char* user = "user1"; char* pass = "pass1"; sqlite3_reset(stmt); sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":username"), (char *)user, (int)strlen(user), SQLITE_TRANSIENT); sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":password"), (char *)pass, (int)strlen(pass), SQLITE_TRANSIENT); if (sqlite3_step(stmt) != SQLITE_DONE){ printf("inserting user data failed!"); exit( -1 ); } sqlite3_reset(stmt); sqlite3_clear_bindings(stmt); sqlite3_finalize(stmt); sqlite3_close( db ); sqlite3_shutdown(); }
查看原文:http://www.mydoop.com/2017/04/sqlite-%e7%bb%91%e5%ae%9a%e6%95%b0%e6%8d%ae%e6%93%8d%e4%bd%9c/
sqlite 绑定数据操作
最新推荐文章于 2023-04-07 16:18:57 发布