SQLite 使用者自訂函數舉例

來源:互聯網
上載者:User
SQLite 使用者自訂函數舉例
 
作者:tamsyn  來源:dongqiang@gmail.com  時間:2007-3-20  【 字型:大 中 小 】 〖 雙擊滾屏 〗
 
 

#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/n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("/n");
   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/n", argv[0]);
  exit(1);
   }
   rc = sqlite3_open(argv[1], &db);
   if( rc ){
  fprintf(stderr, "Can't open database: %s/n", 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/n", zErrMsg);
   }

   sqlite3_close(db);
   return 0;

}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.