CGI如何用C控制SQLite3?
【问题描述】利用C编写CGI程序,如何控制SQLite3,进行基本的数据库操作?
【简介】
需要建立的变量
- sqlite3 *db;
- int nrow = 0, ncolumn = 0;
- char **azResult = NULL;
- char *zErrMsg = 0;
- char sql[500];
- int rc = 0;
需要包含的头文件
- #include <sqlite3.h>
1 打开数据库(open)
- rc = sqlite3_open("test.db", &db);
- if (rc)
- {
- printf("Content-type: text/html\n\n");
- fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
- sqlite3_close(db);
- return sql_errror();
- }
其中,sql_error()是自定义的函数。
2 关闭数据库(close)
- sqlite3_close(db);
3 查(select)
- sprintf(sql,
- "select * from user where name='%s' AND passwd='%s'",
- username, passwd);
- rc = sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );
- if (rc != SQLITE_OK)
- {
- printf("Content-type: text/html\n\n");
- fprintf(stderr, "SQL error: %s\n", zErrMsg);
- sqlite3_close(db);
- return sql_errror();
- }
- if(*azResult != NULL)
- {
- printf("Content-type: text/html\n\n");
- int i;
- for( i=0 ; i<( nrow + 1 ) * ncolumn ; i++ )
- printf( "azResult[%d] = %s\n", i , azResult[i] );
- ...
- }
查询的结果保存在**azResult中,为nrow x ncolumn数组。
4 增(insert)
- sprintf(sql,
- "insert into user(name,passwd) values('%s','%s')",
- username,passwd);
- rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
- if (rc != SQLITE_OK)
- {
- fprintf(stderr, "SQL1 error: %s\n", zErrMsg);
- return 1;
- }
回调函数(callback)
- static int callback(void *NotUsed, int argc, char **argv, char **azColName)
- {
- int i = 0;
- printf("Content-type: text/html\n\n");
- for (i=0; i<argc; i++)
- {
- printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
- }
- printf("\n");
- return 0;
- }
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20