返回> 网站首页 

[转载]SQLite用户自定义函数举例

yoours2011-09-15 23:04:14 阅读 1435

简介一边听听音乐,一边写写文章。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#include <assert.h>
#include <sqlite3.h>

#define SELECT_QUERY "SELECT host_id, geturl(desc) FROM host_table;"
void host2url_func(sqlite3_context * ctx, int argc, sqlite3_value ** argv)
{
if (argc != 1) return;
char * httpurl = NULL;
switch(sqlite3_value_type(argv[0]))
{
case SQLITE_NULL:
{
sqlite3_result_text(ctx, "NULL", 4, SQLITE_STATIC);
break;
}
case SQLITE_TEXT:
{
httpurl = (char *) malloc(strlen(sqlite3_value_text(argv[0])) + 8);
if (httpurl == 0) return;
sprintf(httpurl, "http://%s", sqlite3_value_text(argv[0]));
sqlite3_result_text(ctx, httpurl, strlen(httpurl), SQLITE_TRANSIENT);
free(httpurl);
httpurl = NULL;
break;
}
default:
sqlite3_result_text(ctx, "about:blank", 11, SQLITE_STATIC);
}
}

// 回调函数,用于显示查询结果
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
int i;
for(i=0; i <argc; i++)
{
printf("%s = %s ", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf(" ");
return 0;
}

int main(int argc, char **argv)
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if(argc!=3)
{
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT ", argv[0]);
exit(1);
}

rc = sqlite3_open(argv[1], &db);
if(rc)
{
fprintf(stderr, "Can't open database: %s ", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}

        // 注册扩展的函数
sqlite3_create_function(db, "geturl", 1, SQLITE_ANY, NULL, host2url_func, NULL, NULL);
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if(rc!=SQLITE_OK)
{
fprintf(stderr, "SQL error: %s ", zErrMsg);
}

sqlite3_close(db);
return 0;
}

微信小程序扫码登陆

文章评论

1435人参与,0条评论