【问题描述】利用C编写CGI程序,如何控制sqlite3,进行基本的数据库操作?
【简介】
需要建立的变量
sqlite3 *db;
int nrow = 0, ncolumn = 0;
char **azResult = NULL;
char *zErrMsg = 0;
char sql[500];
int rc = 0;
需要包含的头文件
#include
备注:详见搭建sqlite3嵌入式开发环境,安装后,会产生一个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 {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
5 改(update)
sprintf(sql,
"update user set userid='%s' where name='%s'",
userid,username);
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf(stderr, "SQL1 error: %s\n", zErrMsg);
return 1;
}
6 删(delete)
sprintf(sql,
"delete from user where name='%s'",
username);
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf(stderr, "SQL1 error: %s\n", zErrMsg);
return 1;
}
7 创建表
sprintf(sql,
"create table user(name varchar(20), passwd varchar(20))");
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf(stderr, "SQL1 error: %s\n", zErrMsg);
return 1;
}
8 删除表
sprintf(sql,
"drop table user");
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK)
{
fprintf(stderr, "SQL1 error: %s\n", zErrMsg);
return 1;
}
其他操作相类似,不再赘述。详细请参考:
http://www.w3school.com.cn/sql/sql_drop.asp
http://www.sqlite.org/sqlite.html
如何编译,请参见c调用sqlite3的编译方法