您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ sqlite3_exec函数代码示例

51自学网 2021-06-03 08:15:18
  C++
这篇教程C++ sqlite3_exec函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中sqlite3_exec函数的典型用法代码示例。如果您正苦于以下问题:C++ sqlite3_exec函数的具体用法?C++ sqlite3_exec怎么用?C++ sqlite3_exec使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了sqlite3_exec函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: main

int main (int argc, char **argv) {  sqlite3 *db;          // Definimos un puntero a la base de datos  char *errMsg = 0;     // Variable para el mensaje de error  int rc;               // Variable para el retorno de la sentencia  sqlite3_stmt *result; // Puntero a la respuesta de la consulta  // Abro la conexión con la base de datos  rc = sqlite3_open("BDPrueba.sqlite", &db);  // Compruebo que no hay error  if (rc != SQLITE_OK) {    fprintf(stderr, "No se puede acceder a la base de datos: %s./n", sqlite3_errmsg(db));    sqlite3_close(db);    return(1);  }  // Borro la tabla si no existe  rc = sqlite3_exec(db, "DROP TABLE IF EXISTS Empresa", NULL, NULL, &errMsg);  if (rc != SQLITE_OK) {    fprintf(stderr, "Error al borrar la tabla: %s./n", errMsg);    sqlite3_free(errMsg);    sqlite3_close(db);    return(2);  }  // Creo la tabla Empresa  rc = sqlite3_exec(db, "CREATE TABLE Empresa (IdEmpresa INTEGER PRIMARY KEY, Nombre CHAR[250])", NULL, NULL, &errMsg);  if (rc != SQLITE_OK) {    fprintf(stderr, "Error al crear la tabla: %s./n", errMsg);    sqlite3_free(errMsg);    sqlite3_close(db);    return(2);  }  // Inserto un par de registros  rc = sqlite3_exec(db, "INSERT INTO Empresa VALUES( 1, 'Empresa A')", NULL, NULL, &errMsg);  if (rc != SQLITE_OK) {    fprintf(stderr, "Error al crear el primer registro: %s./n", errMsg);    sqlite3_free(errMsg);    sqlite3_close(db);    return(2);  }  rc = sqlite3_exec(db, "INSERT INTO Empresa VALUES( 2, 'Empresa B')", NULL, NULL, &errMsg);  if (rc != SQLITE_OK) {    fprintf(stderr, "Error al crear el segundo registro: %s./n", errMsg);    sqlite3_free(errMsg);    sqlite3_close(db);    return(2);  }  // Consulta a realizar sobre la tabla.  // En este caso quiero los campos idEmpresa y Nombre de la tabla Empresa  rc = sqlite3_prepare(db, "SELECT idEmpresa,Nombre FROM Empresa", -1, &result, NULL);  // Compruebo que no hay error  if (rc != SQLITE_OK) {    fprintf(stderr, "Error en la consulta: %s./n", sqlite3_errmsg(db));    sqlite3_close(db);    return(3);  }  // Bucle de presentación en pantalla del resultado de la consulta  while ( sqlite3_step(result) == SQLITE_ROW) {    fprintf(stderr, "El Id y nombre de la empresa son:  %i - %s./n", sqlite3_column_int(result, 0)                                                                   , sqlite3_column_text(result, 1));  }  // Cierro la conexión  sqlite3_close(db);  return 0;}
开发者ID:Ralonsoafl,项目名称:flokibooks,代码行数:68,


示例2: register_android_functions

extern "C" int register_android_functions(sqlite3 * handle, int utf16Storage){    int err;    UErrorCode status = U_ZERO_ERROR;    UCollator * collator = ucol_open(NULL, &status);    if (U_FAILURE(status)) {        return -1;    }    if (utf16Storage) {        // Note that text should be stored as UTF-16        err = sqlite3_exec(handle, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);        if (err != SQLITE_OK) {            return err;        }        // Register the UNICODE collation        err = sqlite3_create_collation_v2(handle, "UNICODE", SQLITE_UTF16, collator, collate16,                (void(*)(void*))localized_collator_dtor);    } else {        err = sqlite3_create_collation_v2(handle, "UNICODE", SQLITE_UTF8, collator, collate8,                (void(*)(void*))localized_collator_dtor);    }    if (err != SQLITE_OK) {        return err;    }    // Register the PHONE_NUM_EQUALS function    err = sqlite3_create_function(        handle, "PHONE_NUMBERS_EQUAL", 2,        SQLITE_UTF8, NULL, phone_numbers_equal, NULL, NULL);    if (err != SQLITE_OK) {        return err;    }    // Register the PHONE_NUM_EQUALS function with an additional argument "use_strict"    err = sqlite3_create_function(        handle, "PHONE_NUMBERS_EQUAL", 3,        SQLITE_UTF8, NULL, phone_numbers_equal, NULL, NULL);    if (err != SQLITE_OK) {        return err;    }    // Register the _DELETE_FILE function    err = sqlite3_create_function(handle, "_DELETE_FILE", 1, SQLITE_UTF8, NULL, delete_file, NULL, NULL);    if (err != SQLITE_OK) {        return err;    }#if ENABLE_ANDROID_LOG    // Register the _LOG function    err = sqlite3_create_function(handle, "_LOG", 1, SQLITE_UTF8, NULL, android_log, NULL, NULL);    if (err != SQLITE_OK) {        return err;    }#endif    // Register the GET_PHONEBOOK_INDEX function    err = sqlite3_create_function(handle,        "GET_PHONEBOOK_INDEX",        2, SQLITE_UTF8, NULL,        get_phonebook_index,        NULL, NULL);    if (err != SQLITE_OK) {        return err;    }    return SQLITE_OK;}
开发者ID:Andproject,项目名称:platform_external_sqlite,代码行数:71,


示例3: sqlcipher_codec_ctx_migrate

int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) {  u32 meta;  int rc = 0;  int command_idx = 0;  int password_sz;  int saved_flags;  int saved_nChange;  int saved_nTotalChange;  void (*saved_xTrace)(void*,const char*);  Db *pDb = 0;  sqlite3 *db = ctx->pBt->db;  const char *db_filename = sqlite3_db_filename(db, "main");  char *migrated_db_filename = sqlite3_mprintf("%s-migrated", db_filename);  char *pragma_hmac_off = "PRAGMA cipher_use_hmac = OFF;";  char *pragma_4k_kdf_iter = "PRAGMA kdf_iter = 4000;";  char *pragma_1x_and_4k;  char *set_user_version;  char *key;  int key_sz;  int user_version = 0;  int upgrade_1x_format = 0;  int upgrade_4k_format = 0;  static const unsigned char aCopy[] = {    BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */    BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */    BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */    BTREE_USER_VERSION,       0,  /* Preserve the user version */    BTREE_APPLICATION_ID,     0,  /* Preserve the application id */  };  key_sz = ctx->read_ctx->pass_sz + 1;  key = sqlcipher_malloc(key_sz);  memset(key, 0, key_sz);  memcpy(key, ctx->read_ctx->pass, ctx->read_ctx->pass_sz);  if(db_filename){    const char* commands[5];    char *attach_command = sqlite3_mprintf("ATTACH DATABASE '%s-migrated' as migrate KEY '%q';",                                            db_filename, key);    int rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, "", &user_version);    if(rc == SQLITE_OK){      CODEC_TRACE(("No upgrade required - exiting/n"));      goto exit;    }        // Version 2 - check for 4k with hmac format     rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_4k_kdf_iter, &user_version);    if(rc == SQLITE_OK) {      CODEC_TRACE(("Version 2 format found/n"));      upgrade_4k_format = 1;    }    // Version 1 - check both no hmac and 4k together    pragma_1x_and_4k = sqlite3_mprintf("%s%s", pragma_hmac_off,                                             pragma_4k_kdf_iter);    rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_1x_and_4k, &user_version);    sqlite3_free(pragma_1x_and_4k);    if(rc == SQLITE_OK) {      CODEC_TRACE(("Version 1 format found/n"));      upgrade_1x_format = 1;      upgrade_4k_format = 1;    }    if(upgrade_1x_format == 0 && upgrade_4k_format == 0) {      CODEC_TRACE(("Upgrade format not determined/n"));      goto handle_error;    }    set_user_version = sqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version);    commands[0] = upgrade_4k_format == 1 ? pragma_4k_kdf_iter : "";    commands[1] = upgrade_1x_format == 1 ? pragma_hmac_off : "";    commands[2] = attach_command;    commands[3] = "SELECT sqlcipher_export('migrate');";    commands[4] = set_user_version;          for(command_idx = 0; command_idx < ArraySize(commands); command_idx++){      const char *command = commands[command_idx];      if(strcmp(command, "") == 0){        continue;      }      rc = sqlite3_exec(db, command, NULL, NULL, NULL);      if(rc != SQLITE_OK){        break;      }    }    sqlite3_free(attach_command);    sqlite3_free(set_user_version);    sqlcipher_free(key, key_sz);        if(rc == SQLITE_OK){      Btree *pDest;      Btree *pSrc;      int i = 0;      if( !db->autoCommit ){        CODEC_TRACE(("cannot migrate from within a transaction"));        goto handle_error;      }//.........这里部分代码省略.........
开发者ID:Amazeus-Mozart,项目名称:sqlcipher,代码行数:101,


示例4: SQLI_cache_dbop

int SQLI_cache_dbop(struct DBdesc *db, struct db_cache *cache_elem, struct insert_data *idata){  char *ptr_values, *ptr_where, *ptr_mv, *ptr_set, *ptr_insert;  int num=0, num_set=0, ret=0, have_flows=0, len=0;  if (idata->mv.last_queue_elem) {    ret = sqlite3_exec(db->desc, multi_values_buffer, NULL, NULL, NULL);    Log(LOG_DEBUG, "DEBUG ( %s/%s ): %d INSERT statements sent to the SQLite database./n",                config.name, config.type, idata->mv.buffer_elem_num);    if (ret) goto signal_error;    idata->iqn++;    idata->mv.buffer_elem_num = FALSE;    idata->mv.buffer_offset = 0;    return FALSE;  }    if (config.what_to_count & COUNT_FLOWS) have_flows = TRUE;  /* constructing sql query */  ptr_where = where_clause;  ptr_values = values_clause;   ptr_set = set_clause;  ptr_insert = insert_full_clause;  memset(where_clause, 0, sizeof(where_clause));  memset(values_clause, 0, sizeof(values_clause));  memset(set_clause, 0, sizeof(set_clause));  memset(insert_full_clause, 0, sizeof(insert_full_clause));  for (num = 0; num < idata->num_primitives; num++)    (*where[num].handler)(cache_elem, idata, num, &ptr_values, &ptr_where);  if (cache_elem->flow_type == NF9_FTYPE_EVENT || cache_elem->flow_type == NF9_FTYPE_OPTION) {    for (num_set = 0; set_event[num_set].type; num_set++)      (*set_event[num_set].handler)(cache_elem, idata, num_set, &ptr_set, NULL);  }  else {    for (num_set = 0; set[num_set].type; num_set++)      (*set[num_set].handler)(cache_elem, idata, num_set, &ptr_set, NULL);  }    /* sending UPDATE query a) if not switched off and     b) if we actually have something to update */  if (!config.sql_dont_try_update && num_set) {    strncpy(sql_data, update_clause, SPACELEFT(sql_data));    strncat(sql_data, set_clause, SPACELEFT(sql_data));    strncat(sql_data, where_clause, SPACELEFT(sql_data));    ret = sqlite3_exec(db->desc, sql_data, NULL, NULL, NULL);    if (ret) goto signal_error;   }  if (config.sql_dont_try_update || !num_set || (sqlite3_changes(db->desc) == 0)) {    /* UPDATE failed, trying with an INSERT query */     if (cache_elem->flow_type == NF9_FTYPE_EVENT || cache_elem->flow_type == NF9_FTYPE_OPTION) {      strncpy(insert_full_clause, insert_clause, SPACELEFT(insert_full_clause));      strncat(insert_full_clause, insert_nocounters_clause, SPACELEFT(insert_full_clause));      strncat(ptr_values, ")", SPACELEFT(values_clause));    }    else {      strncpy(insert_full_clause, insert_clause, SPACELEFT(insert_full_clause));      strncat(insert_full_clause, insert_counters_clause, SPACELEFT(insert_full_clause));#if defined HAVE_64BIT_COUNTERS      if (have_flows) snprintf(ptr_values, SPACELEFT(values_clause), ", %llu, %llu, %llu)", cache_elem->packet_counter, cache_elem->bytes_counter, cache_elem->flows_counter);      else snprintf(ptr_values, SPACELEFT(values_clause), ", %llu, %llu)", cache_elem->packet_counter, cache_elem->bytes_counter);#else      if (have_flows) snprintf(ptr_values, SPACELEFT(values_clause), ", %lu, %lu, %lu)", cache_elem->packet_counter, cache_elem->bytes_counter, cache_elem->flows_counter);      else snprintf(ptr_values, SPACELEFT(values_clause), ", %lu, %lu)", cache_elem->packet_counter, cache_elem->bytes_counter);#endif    }        strncpy(sql_data, insert_full_clause, sizeof(sql_data));    strncat(sql_data, values_clause, SPACELEFT(sql_data));    if (config.sql_multi_values) {      multi_values_handling:      len = config.sql_multi_values-idata->mv.buffer_offset;      if (strlen(values_clause) < len) {	if (idata->mv.buffer_elem_num) {	  strcpy(multi_values_buffer+idata->mv.buffer_offset, "; ");	  idata->mv.buffer_offset++;	  idata->mv.buffer_offset++;	}	ptr_mv = multi_values_buffer+idata->mv.buffer_offset;	strcpy(multi_values_buffer+idata->mv.buffer_offset, sql_data); 	idata->mv.buffer_offset += strlen(ptr_mv);        idata->mv.buffer_elem_num++;      }      else {	if (idata->mv.buffer_elem_num) {	  ret = sqlite3_exec(db->desc, multi_values_buffer, NULL, NULL, NULL);	  Log(LOG_DEBUG, "DEBUG ( %s/%s ): %d INSERT statements sent to the SQLite database./n",		config.name, config.type, idata->mv.buffer_elem_num);	  if (ret) goto signal_error;	  idata->iqn++;	  idata->mv.buffer_elem_num = FALSE;	  idata->mv.head_buffer_elem = FALSE;	  idata->mv.buffer_offset = 0;	  goto multi_values_handling;	}//.........这里部分代码省略.........
开发者ID:CodethinkLabs,项目名称:pmacct,代码行数:101,


示例5: sqlite3_get_table

/*** Query the database.  But instead of invoking a callback for each row,** malloc() for space to hold the result and return the entire results** at the conclusion of the call.**** The result that is written to ***pazResult is held in memory obtained** from malloc().  But the caller cannot free this memory directly.  ** Instead, the entire table should be passed to sqlite3_free_table() when** the calling procedure is finished using it.*/SQLITE_API int sqlite3_get_table(  sqlite3 *db,                /* The database on which the SQL executes */  const char *zSql,           /* The SQL to be executed */  char ***pazResult,          /* Write the result table here */  int *pnRow,                 /* Write the number of rows in the result here */  int *pnColumn,              /* Write the number of columns of result here */  char **pzErrMsg             /* Write error messages here */){  int rc;  TabResult res;  *pazResult = 0;  if( pnColumn ) *pnColumn = 0;  if( pnRow ) *pnRow = 0;  if( pzErrMsg ) *pzErrMsg = 0;  res.zErrMsg = 0;  res.nRow = 0;  res.nColumn = 0;  res.nData = 1;  res.nAlloc = 20;  res.rc = SQLITE_OK;  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );  if( res.azResult==0 ){     db->errCode = SQLITE_NOMEM;     return SQLITE_NOMEM;  }  res.azResult[0] = 0;  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);  if( (rc&0xff)==SQLITE_ABORT ){    sqlite3_free_table(&res.azResult[1]);    if( res.zErrMsg ){      if( pzErrMsg ){        sqlite3_free(*pzErrMsg);        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);      }      sqlite3_free(res.zErrMsg);    }    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */    return res.rc;  }  sqlite3_free(res.zErrMsg);  if( rc!=SQLITE_OK ){    sqlite3_free_table(&res.azResult[1]);    return rc;  }  if( res.nAlloc>res.nData ){    char **azNew;    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );    if( azNew==0 ){      sqlite3_free_table(&res.azResult[1]);      db->errCode = SQLITE_NOMEM;      return SQLITE_NOMEM;    }    res.azResult = azNew;  }  *pazResult = &res.azResult[1];  if( pnColumn ) *pnColumn = res.nColumn;  if( pnRow ) *pnRow = res.nRow;  return rc;}
开发者ID:jiankangshiye,项目名称:mysqlite,代码行数:72,


示例6: main

int main(int argc,char* argv[]){  sqlite3 *db;  char *zErrMsg=0;  char file[100];  char *sql;  int i;  sqlite3_stmt *prepared_insert,*prepared_delete,*prepared_replace,*prepared_source_redirect;  listNode* root=calloc(1,sizeof(listNode));  strcat(file,getenv("HOME"));  strncat(file,"/freshen.db",13);  int rc;  rc=sqlite3_open(file,&db);  if(rc){    fprintf(stderr,"Can't open database:%s/n",sqlite3_errmsg(db));    exit(0);  }else{    fprintf(stderr,"database opened successfully/n");  }  sql=CREATE_TABLE;  rc=sqlite3_exec(db,sql,callback,0,&zErrMsg);  if(rc!=SQLITE_OK){    fprintf(stderr,"SQL Error:%s/n",zErrMsg);    sqlite3_free(zErrMsg);  }else{    fprintf(stderr,"Table created sucessfully/n");  }  rc=sqlite3_prepare_v2(db,"insert into FILES (DESTINATION,SOURCE,DANGEROUS) values (?,?,?);",-1,&prepared_insert,NULL);  if(rc!=SQLITE_OK){    //write this sometime  }  rc=sqlite3_prepare_v2(db,"delete from FILES where DESTINATION = ?",-1,&prepared_delete,NULL);  if(rc!=SQLITE_OK){    //do something here sometime.  }  rc=sqlite3_prepare_v2(db,"update FILES set SOURCE = ? where DESTINATION = ?",-1,&prepared_replace,NULL);  if(rc!=SQLITE_OK){    //Needs to be written  }  rc=sqlite3_prepare_v2(db,"UPDATE FILES SET SOURCE = ? WHERE SOURCE = ?",-1,&prepared_source_redirect,NULL);  if(rc!=SQLITE_OK){    //This sort of thing might not need to actually be written, after all, they    //should compile to the same thing each time.    fprintf(stderr,"Something broke!/n");  }  for(i=1;i<argc;i++){    if(strcmp(argv[i],"-insert")==0){      char *dest=argv[i+1];      char *src=argv[i+2];      char destpath[PATH_MAX+1],        srcpath[PATH_MAX+1];      if(!isArgFile(dest)){        fprintf(stderr,"-insert requires two arguments <destination file> <source file> [-dangerous]?/n%s is not visible to this as a file/n",dest);        exit(1);      }      if(!isArgFile(src)){        fprintf(stderr,"-insert requires two arguments <destination file> <source file> [-dangerous]?/n%s is not visible to this as a file/n",src);        exit(1);      }      if(!fileExists(src))        {          fprintf(stderr,"%s does not exist, source files must exist/n",src);          exit(1);        }      realpath(dest,destpath);      realpath(src,srcpath);      i+=2;      short dangerous=0;      if(argc>=i+2){        if(strcmp(argv[i+1],"-dangerous")==0)          {            dangerous=1;            i++;          }      }      if(sqlite3_bind_text(prepared_insert,1,destpath,-1,SQLITE_STATIC)!=SQLITE_OK)        fprintf(stderr,"Failed to bind destination/n");      if(sqlite3_bind_text(prepared_insert,2,srcpath,-1,SQLITE_STATIC)!=SQLITE_OK)        fprintf(stderr,"Failed to bind source/n");      if(sqlite3_bind_int(prepared_insert,3,dangerous)!=SQLITE_OK)        fprintf(stderr,"Failed to bind dangerous/n");      rc=sqlite3_step(prepared_insert);      if(rc!=SQLITE_DONE){        fprintf(stderr,"Didn't run right: %s/n",sqlite3_errstr(rc));      }      sqlite3_reset(prepared_insert);//Reset prepared statement    }else if(strcmp(argv[i],"-freshen")==0){      sqlite3_exec(db,"select * from FILES;",freshen,(void*)root,&zErrMsg);      listNode* r=root;      struct stat srcbuf,dstbuf;      short destination_exists=1,skip_danger=0;      char can_replace=1;      struct utimbuf replacement_time;      if(argc>i+1&&strcmp(argv[i+1],"-safe-only")){        skip_danger=1;        i++;      }      while(r){        rc=stat(r->destination,&dstbuf);//.........这里部分代码省略.........
开发者ID:jaked122,项目名称:file-freshener,代码行数:101,


示例7: rec_sqlite_writeTable

bool rec_sqlite_writeTable (){	traceLastFunc( "rec_sqlite_writeTable()" );	sqlite3 *rec_db;	char sql_cmd[1024];	char *errmsgs = NULL;	int ret_exists;	if ( rec_state == RECORDING_RECORD )	{		cheat_state_text( "Can't save while recording." );		return false;	}	if ( rec_maxNum <= 0 )	{		cheat_state_text( "Nothing to be saved." );		return false;	}	if ( sqlite3_open( REC_DB_NAME, &rec_db ) != SQLITE_OK )	{		Log( "SQLite - Error while connecting: %s", sqlite3_errmsg(rec_db) );		sqlite3_close( rec_db );		return false;	}	for ( int i = 0; i < 64; i++ ) // max default name	{		_snprintf_s( sql_cmd, sizeof(sql_cmd)-1, "route%i", i );		ret_exists = sqliteDB_checkTableExists( rec_db, sql_cmd );		// continue, if table already exists		if ( ret_exists == 1 )			continue;		// quit function on fail		if ( ret_exists == -1 )		{			sqlite3_close( rec_db );			return false;		}		// create table with default name 'route..'		_snprintf_s( sql_cmd, sizeof(sql_cmd)-1, "CREATE TABLE 'route%i'(", i );		_snprintf_s( sql_cmd, sizeof(sql_cmd)-1, "%s 'index' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," /			"'maxNum' INTEGER NULL DEFAULT NULL," /			"'angle1' REAL NOT NULL,'angle2' REAL NOT NULL,'angle3' REAL NOT NULL,'angle4' REAL NOT NULL," /			"'angle5' REAL NOT NULL,'angle6' REAL NOT NULL,"/			"'spin1' REAL NOT NULL,'spin2' REAL NOT NULL,'spin3' REAL NOT NULL," /			"'speed1' REAL NOT NULL,'speed2' REAL NOT NULL,'speed3' REAL NOT NULL," /			"'pos1' REAL NOT NULL,'pos2' REAL NOT NULL,'pos3' REAL NOT NULL);"			, sql_cmd );		sqlite3_exec( rec_db, sql_cmd, NULL, NULL, &errmsgs );		if ( errmsgs != NULL )		{			Log( "SQLite - Error (executing CREATE TABLE statement): %s", errmsgs );			sqlite3_close( rec_db );			return false;		}		// add our data into the new table		for ( int j = 0; j < rec_maxNum && j < (REC_ARRAYSIZE-1); j++ )		{			if ( j != 0 )				_snprintf_s( sql_cmd, sizeof(sql_cmd)-1, "INSERT INTO 'route%i' VALUES( null, null,", i );			else				_snprintf_s( sql_cmd, sizeof(sql_cmd)-1, "INSERT INTO 'route%i' VALUES( null, %i,", i, rec_maxNum );			_snprintf_s( sql_cmd, sizeof(sql_cmd)-1, "%s %0.2f, %0.2f, %0.2f, %0.2f,"				"%0.2f, %0.2f," /				"%0.2f, %0.2f, %0.2f," /				"%0.2f, %0.2f, %0.2f," /				"%0.2f, %0.2f, %0.2f" /				");", 				sql_cmd, rec_angle[j][0], rec_angle[j][1], rec_angle[j][2], rec_angle[j][3], 				rec_angle[j][4], rec_angle[j][5],				rec_spin[j][0], rec_spin[j][1], rec_spin[j][2],				rec_speed[j][0], rec_speed[j][1], rec_speed[j][2],				rec_pos[j][0], rec_pos[j][1], rec_pos[j][2] );			//Log( sql_cmd );			sqlite3_exec( rec_db, sql_cmd, NULL, NULL, &errmsgs );			if ( errmsgs != NULL )			{				Log( "SQLite - Error (executing INSERT INTO statement): %s", errmsgs );				sqlite3_close( rec_db );				return false;			}		}		cheat_state_text( "saved to 'route%i'", i );		break;	}	sqlite3_close( rec_db );	return true;}
开发者ID:mishannn,项目名称:m0d_sa,代码行数:96,


示例8: try_to_open_db

static int try_to_open_db(const char *filename, struct memblock *mem, struct dive_table *table){	sqlite3 *handle;	char dm4_test[] = "select count(*) from sqlite_master where type='table' and name='Dive' and sql like '%ProfileBlob%'";	char dm5_test[] = "select count(*) from sqlite_master where type='table' and name='Dive' and sql like '%SampleBlob%'";	char shearwater_test[] = "select count(*) from sqlite_master where type='table' and name='system' and sql like '%dbVersion%'";	char cobalt_test[] = "select count(*) from sqlite_master where type='table' and name='TrackPoints' and sql like '%DepthPressure%'";	char divinglog_test[] = "select count(*) from sqlite_master where type='table' and name='DBInfo' and sql like '%PrgName%'";	int retval;	retval = sqlite3_open(filename, &handle);	if (retval) {		fprintf(stderr, "Database connection failed '%s'./n", filename);		return 1;	}	/* Testing if DB schema resembles Suunto DM5 database format */	retval = sqlite3_exec(handle, dm5_test, &db_test_func, 0, NULL);	if (!retval) {		retval = parse_dm5_buffer(handle, filename, mem->buffer, mem->size, table);		sqlite3_close(handle);		return retval;	}	/* Testing if DB schema resembles Suunto DM4 database format */	retval = sqlite3_exec(handle, dm4_test, &db_test_func, 0, NULL);	if (!retval) {		retval = parse_dm4_buffer(handle, filename, mem->buffer, mem->size, table);		sqlite3_close(handle);		return retval;	}	/* Testing if DB schema resembles Shearwater database format */	retval = sqlite3_exec(handle, shearwater_test, &db_test_func, 0, NULL);	if (!retval) {		retval = parse_shearwater_buffer(handle, filename, mem->buffer, mem->size, table);		sqlite3_close(handle);		return retval;	}	/* Testing if DB schema resembles Atomic Cobalt database format */	retval = sqlite3_exec(handle, cobalt_test, &db_test_func, 0, NULL);	if (!retval) {		retval = parse_cobalt_buffer(handle, filename, mem->buffer, mem->size, table);		sqlite3_close(handle);		return retval;	}	/* Testing if DB schema resembles Divinglog database format */	retval = sqlite3_exec(handle, divinglog_test, &db_test_func, 0, NULL);	if (!retval) {		retval = parse_divinglog_buffer(handle, filename, mem->buffer, mem->size, table);		sqlite3_close(handle);		return retval;	}	sqlite3_close(handle);	return retval;}
开发者ID:torvalds,项目名称:subsurface,代码行数:61,


示例9: rspamd_sqlite3_wait

//.........这里部分代码省略.........					errno, "cannot create sqlite file %s: %s",					path, strerror (errno));			return NULL;		}		/* At this point we have database created */		create = FALSE;		has_lock = FALSE;	}	else {		msg_debug_pool ("locking %s to block other processes", lock_path);		g_assert (rspamd_file_lock (lock_fd, FALSE));		has_lock = TRUE;	}	if ((rc = sqlite3_open_v2 (path, &sqlite,			flags, NULL)) != SQLITE_OK) {#if SQLITE_VERSION_NUMBER >= 3008000		g_set_error (err, rspamd_sqlite3_quark (),				rc, "cannot open sqlite db %s: %s",				path, sqlite3_errstr (rc));#else		g_set_error (err, rspamd_sqlite3_quark (),				rc, "cannot open sqlite db %s: %d",				path, rc);#endif		return NULL;	}	if (create) {		if (sqlite3_exec (sqlite, sqlite_wal, NULL, NULL, NULL) != SQLITE_OK) {			msg_warn_pool ("WAL mode is not supported (%s), locking issues might occur",					sqlite3_errmsg (sqlite));		}		if (sqlite3_exec (sqlite, exclusive_lock_sql, NULL, NULL, NULL) != SQLITE_OK) {			msg_warn_pool ("cannot exclusively lock database to create schema: %s",					sqlite3_errmsg (sqlite));		}		if (sqlite3_exec (sqlite, create_sql, NULL, NULL, NULL) != SQLITE_OK) {			g_set_error (err, rspamd_sqlite3_quark (),					-1, "cannot execute create sql `%s`: %s",					create_sql, sqlite3_errmsg (sqlite));			sqlite3_close (sqlite);			rspamd_file_unlock (lock_fd, FALSE);			unlink (lock_path);			close (lock_fd);			return NULL;		}		sqlite3_close (sqlite);		/* Reopen in normal mode */		msg_debug_pool ("reopening %s in normal mode", path);		flags &= ~SQLITE_OPEN_CREATE;		if ((rc = sqlite3_open_v2 (path, &sqlite,				flags, NULL)) != SQLITE_OK) {	#if SQLITE_VERSION_NUMBER >= 3008000			g_set_error (err, rspamd_sqlite3_quark (),
开发者ID:skibbipl,项目名称:rspamd,代码行数:67,


示例10: sqlite3_exec

// "SELECT fold, id, rev, features FROM..."int Database::GetTuples(const std::string& q, std::vector<tuple_t>* r) const{	return sqlite3_exec(m_db, q.c_str(), Database::get_vector,			static_cast<void*>(r), NULL);}
开发者ID:etcwilde,项目名称:Artificial-Intelligence,代码行数:6,


示例11: siconv

void database::add_trade(const TradeGateway::ExecutionReport *pTrade){	if( !this->is_connected() )		this->connect();	if( pTrade->lastQty == 0 ) return;	// gb2312 to utf8	std::string text = siconv(pTrade->ordRejReason,"GB2312","UTF-8");	std::ostringstream sql;			sql << "BEGIN;";	sql << "INSERT INTO dt_trades VALUES ("		<< "'" << pTrade->accountId << "',"		<< "'" << pTrade->ordId<< "',"		<< "'" << pTrade->execId << "',"		<< ""  << pTrade->type<< ","		<< "/"" << text<< "/","		<< ""  << pTrade->lastQty << ","		<< ""  << pTrade->lastPx<< ","		<< ""  << pTrade->tradeDate<< ","		<< ""  << pTrade->transactTime<< ");";		//更新委托表	TradeGateway::OrderStatus os;	switch( pTrade->type )	{	case TradeGateway::EtCanceled:		os =  TradeGateway::Canceled;		sql << "UPDATE dt_orders SET "			<< "ordStatus =" << os << ","			<< "cumQty=(ordQty-" << abs((int)pTrade->lastQty) << "),"			<< "text=/"" << text << "/","			<< "leavesQty="  <<  0 << " "			<< "WHERE (ordId='" <<  pTrade->ordId << "') "			<< "AND (accountId='" << pTrade->accountId << "') "			<< "AND (date=" << pTrade->tradeDate << ");";		break;	case TradeGateway::EtRejected:		os =  TradeGateway::Rejected;		sql << "UPDATE dt_orders SET "			<< "ordStatus =" << os << ","			<< "cumQty=(ordQty-" << abs((int)pTrade->lastQty) << "),"			<< "text=/"" << text << "/","			<< "leavesQty="  <<  0 << " "			<< "WHERE (ordId='" <<  pTrade->ordId << "') "			<< "AND (accountId='" << pTrade->accountId << "') "			<< "AND (date=" << pTrade->tradeDate << ");";		break;	case TradeGateway::EtStopped:		os =  TradeGateway::Stopped;		sql << "UPDATE dt_orders SET "			<< "ordStatus =" << os << ","			<< "cumQty=(ordQty-" << abs((int)pTrade->lastQty) << "),"			<< "text=/"" << text << "/","			<< "leavesQty="  <<  0 << " "			<< "WHERE (ordId='" <<  pTrade->ordId << "') "			<< "AND (accountId='" << pTrade->accountId << "') "			<< "AND (date=" << pTrade->tradeDate << ");";		break;	case TradeGateway::EtTrade:		sql << "UPDATE dt_orders SET "			<< "avgPx=(cumQty*avgPx+" <<pTrade->lastQty*pTrade->lastPx<< ")/(cumQty+"<< pTrade->lastQty << "),"			<< "cumQty=(cumQty+" << pTrade->lastQty << "),"			<< "leavesQty=leavesQty-"  <<  pTrade->lastQty << ","			<< "ordStatus = CASE (leavesQty-"<<pTrade->lastQty <<") WHEN 0 then " << TradeGateway::Filled << " ELSE "<<TradeGateway::Working <<" END "			<< "WHERE (ordId='" <<  pTrade->ordId << "') "			<< "AND (accountId='" << pTrade->accountId << "') "			<< "AND (date=" << pTrade->tradeDate << ");";		break;	}	sql << "COMMIT;";	char *zErrMsg = 0;	int rc = sqlite3_exec(pdb, sql.str().c_str(), NULL, 0, &zErrMsg);	if( rc!=SQLITE_OK )	{		std::ostringstream err ;		err << "SQL error: " << zErrMsg;		sqlite3_free(zErrMsg);		throw err.str();	}}
开发者ID:code4hunter,项目名称:oldpts,代码行数:85,


示例12: OGRSQLiteExecuteSQL

//.........这里部分代码省略.........                         oLayerDesc.osDSName.c_str() );                delete poSQLiteDS;                VSIUnlink(pszTmpDBName);                CPLFree(pszTmpDBName);                return NULL;            }                        poLayer = poOtherDS->GetLayerByName(oLayerDesc.osLayerName);            if( poLayer == NULL )            {                CPLError(CE_Failure, CPLE_AppDefined,                         "Cannot find layer '%s' in '%s'",                         oLayerDesc.osLayerName.c_str(),                         oLayerDesc.osDSName.c_str() );                delete poOtherDS;                delete poSQLiteDS;                VSIUnlink(pszTmpDBName);                CPLFree(pszTmpDBName);                return NULL;            }            osTableName = oLayerDesc.osSubstitutedName;            nExtraDS = OGR2SQLITE_AddExtraDS(poModule, poOtherDS);        }        osSQL.Printf("CREATE VIRTUAL TABLE /"%s/" USING VirtualOGR(%d,'%s',%d)",                OGRSQLiteEscapeName(osTableName).c_str(),                nExtraDS,                OGRSQLiteEscape(oLayerDesc.osLayerName).c_str(),                bFoundOGRStyle);        char* pszErrMsg = NULL;        int rc = sqlite3_exec( hDB, osSQL.c_str(),                               NULL, NULL, &pszErrMsg );        if( rc != SQLITE_OK )        {            CPLError(CE_Failure, CPLE_AppDefined,                     "Cannot create virtual table for layer '%s' : %s",                     osTableName.c_str(), pszErrMsg);            sqlite3_free(pszErrMsg);            continue;        }        for(int i=0; i<poLayer->GetLayerDefn()->GetGeomFieldCount(); i++)        {            OGR2SQLITEDealWithSpatialColumn(poLayer, i, oLayerDesc,                                            osTableName, poSQLiteDS, hDB,                                            bSpatialiteDB, oSetLayers,                                            oSetSpatialIndex);        }    }/* -------------------------------------------------------------------- *//*      Reload, so that virtual tables are recognized                   *//* -------------------------------------------------------------------- */    poSQLiteDS->ReloadLayers();/* -------------------------------------------------------------------- *//*      Prepare the statement.                                          *//* -------------------------------------------------------------------- */    /* This will speed-up layer creation */    /* ORDER BY are costly to evaluate and are not necessary to establish */    /* the layer definition. */    int bUseStatementForGetNextFeature = TRUE;    int bEmptyLayer = FALSE;
开发者ID:rashadkm,项目名称:lib_gdal,代码行数:67,


示例13: OGR2SQLITEDealWithSpatialColumn

//.........这里部分代码省略.........            int nCoordDimension = 2;            if( wkbHasZ((OGRwkbGeometryType)nGeomType) )            {                nGeomType += 1000;                nCoordDimension = 3;            }            osSQL.Printf("INSERT INTO geometry_columns (f_table_name, "                        "f_geometry_column, geometry_type, coord_dimension, "                        "srid, spatial_index_enabled) "                        "VALUES ('%s',Lower('%s'),%d ,%d ,%d, %d)",                        pszLayerNameEscaped,                        pszGeomColEscaped, nGeomType,                        nCoordDimension,                        nSRSId, bCreateSpatialIndex );        }        else        {            const char *pszGeometryType = OGRToOGCGeomType(poLayer->GetGeomType());            if (pszGeometryType[0] == '/0')                pszGeometryType = "GEOMETRY";            osSQL.Printf("INSERT INTO geometry_columns (f_table_name, "                        "f_geometry_column, type, coord_dimension, "                        "srid, spatial_index_enabled) "                        "VALUES ('%s','%s','%s','%s',%d, %d)",                        pszLayerNameEscaped,                        pszGeomColEscaped, pszGeometryType,                        wkbHasZ( poLayer->GetGeomType() ) ? "XYZ" : "XY",                        nSRSId, bCreateSpatialIndex );        }    }#endif // HAVE_SPATIALITE    rc = sqlite3_exec( hDB, osSQL.c_str(), NULL, NULL, NULL );#ifdef HAVE_SPATIALITE/* -------------------------------------------------------------------- *//*      Should we create a spatial index ?.                             *//* -------------------------------------------------------------------- */    if( !bSpatialiteDB || !bCreateSpatialIndex )        return rc == SQLITE_OK;    CPLDebug("SQLITE", "Create spatial index %s", osIdxNameRaw.c_str());    /* ENABLE_VIRTUAL_OGR_SPATIAL_INDEX is not defined */#ifdef ENABLE_VIRTUAL_OGR_SPATIAL_INDEX    osSQL.Printf("CREATE VIRTUAL TABLE /"%s/" USING "                    "VirtualOGRSpatialIndex(%d, '%s', pkid, xmin, xmax, ymin, ymax)",                    osIdxNameEscaped.c_str(),                    nExtraDS,                    OGRSQLiteEscape(oLayerDesc.osLayerName).c_str());    rc = sqlite3_exec( hDB, osSQL.c_str(), NULL, NULL, NULL );    if( rc != SQLITE_OK )    {        CPLDebug("SQLITE",                    "Error occured during spatial index creation : %s",                    sqlite3_errmsg(hDB));    }#else //  ENABLE_VIRTUAL_OGR_SPATIAL_INDEX    rc = sqlite3_exec( hDB, "BEGIN", NULL, NULL, NULL );    osSQL.Printf("CREATE VIRTUAL TABLE /"%s/" "                    "USING rtree(pkid, xmin, xmax, ymin, ymax)",                    osIdxNameEscaped.c_str());
开发者ID:rashadkm,项目名称:lib_gdal,代码行数:66,


示例14: cache_create

static intcache_create(void){#define Q_PRAGMA_CACHE_SIZE "PRAGMA cache_size=%d;"#define Q_PRAGMA_JOURNAL_MODE "PRAGMA journal_mode=%s;"#define Q_PRAGMA_SYNCHRONOUS "PRAGMA synchronous=%d;"  char *errmsg;  int ret;  int cache_size;  char *journal_mode;  int synchronous;  char *query;  // Open db  ret = sqlite3_open(g_db_path, &g_db_hdl);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Could not open database: %s/n", sqlite3_errmsg(g_db_hdl));      sqlite3_close(g_db_hdl);      return -1;    }  // Check cache version  ret = cache_check_version();  if (ret < 0)    {      DPRINTF(E_FATAL, L_CACHE, "Could not check cache database version/n");      sqlite3_close(g_db_hdl);      return -1;    }  else if (ret > 0)    {      ret = cache_create_tables();      if (ret < 0)	{	  DPRINTF(E_FATAL, L_CACHE, "Could not create database tables/n");	  sqlite3_close(g_db_hdl);	  return -1;	}    }  // Set page cache size in number of pages  cache_size = cfg_getint(cfg_getsec(cfg, "sqlite"), "pragma_cache_size_cache");  if (cache_size > -1)    {      query = sqlite3_mprintf(Q_PRAGMA_CACHE_SIZE, cache_size);      ret = sqlite3_exec(g_db_hdl, query, NULL, NULL, &errmsg);      if (ret != SQLITE_OK)	{	  DPRINTF(E_FATAL, L_CACHE, "Error creating query index: %s/n", errmsg);	  sqlite3_free(errmsg);	  sqlite3_close(g_db_hdl);	  return -1;	}    }  // Set journal mode  journal_mode = cfg_getstr(cfg_getsec(cfg, "sqlite"), "pragma_journal_mode");  if (journal_mode)    {      query = sqlite3_mprintf(Q_PRAGMA_JOURNAL_MODE, journal_mode);      ret = sqlite3_exec(g_db_hdl, query, NULL, NULL, &errmsg);      if (ret != SQLITE_OK)	{	  DPRINTF(E_FATAL, L_CACHE, "Error creating query index: %s/n", errmsg);	  sqlite3_free(errmsg);	  sqlite3_close(g_db_hdl);	  return -1;	}    }  // Set synchronous flag  synchronous = cfg_getint(cfg_getsec(cfg, "sqlite"), "pragma_synchronous");  if (synchronous > -1)    {      query = sqlite3_mprintf(Q_PRAGMA_SYNCHRONOUS, synchronous);      ret = sqlite3_exec(g_db_hdl, query, NULL, NULL, &errmsg);      if (ret != SQLITE_OK)	{	  DPRINTF(E_FATAL, L_CACHE, "Error creating query index: %s/n", errmsg);	  sqlite3_free(errmsg);	  sqlite3_close(g_db_hdl);	  return -1;	}    }  DPRINTF(E_DBG, L_CACHE, "Cache created/n");  return 0;#undef Q_PRAGMA_CACHE_SIZE#undef Q_PRAGMA_JOURNAL_MODE#undef Q_PRAGMA_SYNCHRONOUS}
开发者ID:Illuminux,项目名称:forked-daapd,代码行数:99,


示例15: main

int main(void){    int  lfd;    int cfd;    int sfd;    int rdy;        struct sockaddr_in sin;    struct sockaddr_in cin;    int client[FD_SETSIZE];  /* 客户端连接的套接字描述符数组 */    int maxi;    int maxfd;                        /* 最大连接数 */    fd_set rset;    fd_set allset;    socklen_t addr_len;         /* 地址结构长度 */    int i;    int n;    int len;    int opt = 1;   /* 套接字选项 */    char addr_p[20];    sqlite3 *db = NULL;    char *err_msg = NULL;    msg_t msg;    time_t ptime;    char pestime[100] = {0};                                                   /* 对server_addr_in  结构进行赋值  */    bzero(&sin,sizeof(struct sockaddr_in));        /* 先清零 */    sin.sin_family=AF_INET;                     sin.sin_addr.s_addr=htonl(INADDR_ANY);         //表示接受任何ip地址   将ip地址转换成网络字节序    sin.sin_port=htons(PORT);                      //将端口号转换成网络字节序                                                   /* 调用socket函数创建一个TCP协议套接口 */    if((lfd=socket(AF_INET,SOCK_STREAM,0))==-1)    // AF_INET:IPV4;SOCK_STREAM:TCP    {        fprintf(stderr,"Socket error:%s/n/a",strerror(errno));        exit(1);    }    /*设置套接字选项 使用默认选项*/    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));    /* 调用bind函数 将serer_addr结构绑定到sockfd上  */    if(bind(lfd,(struct sockaddr *)(&sin),sizeof(struct sockaddr))==-1)    {        fprintf(stderr,"Bind error:%s/n/a",strerror(errno));        exit(1);    }    /* 开始监听端口   等待客户的请求 */    if(listen(lfd,20)==-1)    {        fprintf(stderr,"Listen error:%s/n/a",strerror(errno));        exit(1);    }    printf("Accepting connections ......./n");    maxfd = lfd;                                /*对最大文件描述符进行初始化*/    maxi = -1;    /*初始化客户端连接描述符集合*/    for(i = 0;i < FD_SETSIZE;i++)    {        client[i] = -1;    }    FD_ZERO(&allset);                     /* 清空文件描述符集合 */    FD_SET(lfd,&allset);                    /* 将监听字设置在集合内 */    int rc = sqlite3_open("chat_room.db",&db);    if(rc != SQLITE_OK)    {        fprintf(stderr,"open database failed %s/n",sqlite3_errmsg(db));    }    char sql_create_user_info[256] = {0};            //保存用户信息    sprintf(sql_create_user_info,"create table user_info(id INTEGER,name TEXT,password TEXT,primary key(id));");    sqlite3_exec(db,sql_create_user_info,NULL,0,&err_msg);    char sql_create_log_info[256] = {0};             //保存已登录用户    sprintf(sql_create_log_info,"create table log_info(id INTEGER,name TEXT,connectfd INTEGER,primary key(id));");    sqlite3_exec(db,sql_create_log_info,NULL,0,&err_msg);    char sql_create_record[256] = {0};               //保存服务器运行记录    sprintf(sql_create_record,"create table record(id INTEGER,name TEXT,size TEXT,target TEXT,msg TEXT,time TEXT,primary key(id));");    sqlite3_exec(db,sql_create_record,NULL,0,&err_msg);    /* 开始服务程序的死循环 */    while(1)//.........这里部分代码省略.........
开发者ID:lr6666,项目名称:duan,代码行数:101,


示例16: cache_daap_query_add

/* Adds the query to the list of queries for which we will build and cache a reply */static intcache_daap_query_add(struct cache_command *cmd){#define Q_TMPL "INSERT OR REPLACE INTO queries (user_agent, query, msec, timestamp) VALUES ('%q', '%q', %d, %" PRIi64 ");"#define Q_CLEANUP "DELETE FROM queries WHERE id NOT IN (SELECT id FROM queries ORDER BY timestamp DESC LIMIT 20);"  char *query;  char *errmsg;  int ret;  if (!cmd->arg.ua)    {      DPRINTF(E_LOG, L_CACHE, "Couldn't add slow query to cache, unknown user-agent/n");      goto error_add;    }  // Currently we are only able to pre-build and cache these reply types  if ( (strncmp(cmd->arg.query, "/databases/1/containers/", strlen("/databases/1/containers/")) != 0) &&       (strncmp(cmd->arg.query, "/databases/1/groups?", strlen("/databases/1/groups?")) != 0) &&       (strncmp(cmd->arg.query, "/databases/1/items?", strlen("/databases/1/items?")) != 0) &&       (strncmp(cmd->arg.query, "/databases/1/browse/", strlen("/databases/1/browse/")) != 0) )    goto error_add;  remove_tag(cmd->arg.query, "session-id");  remove_tag(cmd->arg.query, "revision-number");  query = sqlite3_mprintf(Q_TMPL, cmd->arg.ua, cmd->arg.query, cmd->arg.msec, (int64_t)time(NULL));  if (!query)    {      DPRINTF(E_LOG, L_CACHE, "Out of memory making query string./n");      goto error_add;    }  ret = sqlite3_exec(g_db_hdl, query, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_LOG, L_CACHE, "Error adding query to query list: %s/n", errmsg);      sqlite3_free(query);      sqlite3_free(errmsg);      goto error_add;    }  sqlite3_free(query);  DPRINTF(E_INFO, L_CACHE, "Slow query (%d ms) added to cache: '%s' (user-agent: '%s')/n", cmd->arg.msec, cmd->arg.query, cmd->arg.ua);  free(cmd->arg.ua);  free(cmd->arg.query);  // Limits the size of the cache to only contain replies for 20 most recent queries  ret = sqlite3_exec(g_db_hdl, Q_CLEANUP, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_LOG, L_CACHE, "Error cleaning up query list before update: %s/n", errmsg);      sqlite3_free(errmsg);      return -1;    }  cache_daap_trigger();  return 0; error_add:  if (cmd->arg.ua)    free(cmd->arg.ua);  if (cmd->arg.query)    free(cmd->arg.query);  return -1;#undef Q_CLEANUP#undef Q_TMPL}
开发者ID:Illuminux,项目名称:forked-daapd,代码行数:76,


示例17: sprintf

void CurrentStatic::Update(){	char sql[256];	sprintf(sql, "UPDATE CurrentStatic SET x=%.f, y=%.f, locationId=%d WHERE id=%d;", x, y, currentLocation->id, id);	sqlite3_exec(Game::instance->db, sql, NULL, NULL, NULL);}
开发者ID:insolite,项目名称:RPG,代码行数:6,


示例18: sqlite3InitOne

//.........这里部分代码省略.........    int i;    for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){      rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, i+1, (u32 *)&meta[i]);    }    if( rc ){      sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);      sqlite3BtreeCloseCursor(curMain);      return rc;    }  }else{    memset(meta, 0, sizeof(meta));  }  db->aDb[iDb].schema_cookie = meta[0];  /* If opening a non-empty database, check the text encoding. For the  ** main database, set sqlite3.enc to the encoding of the main database.  ** For an attached db, it is an error if the encoding is not the same  ** as sqlite3.enc.  */  if( meta[4] ){  /* text encoding */    if( iDb==0 ){      /* If opening the main database, set db->enc. */      db->enc = (u8)meta[4];      db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0);    }else{      /* If opening an attached database, the encoding much match db->enc */      if( meta[4]!=db->enc ){        sqlite3BtreeCloseCursor(curMain);        sqlite3SetString(pzErrMsg, "attached databases must use the same"            " text encoding as main database", (char*)0);        return SQLITE_ERROR;      }    }  }  size = meta[2];  if( size==0 ){ size = MAX_PAGES; }  db->aDb[iDb].cache_size = size;  if( iDb==0 ){    db->file_format = meta[1];    if( db->file_format==0 ){      /* This happens if the database was initially empty */      db->file_format = 1;    }    if( db->file_format==2 || db->file_format==3 ){      /* File format 2 is treated exactly as file format 1. New       ** databases are created with file format 1.      */       db->file_format = 1;    }  }  /*  ** file_format==1    Version 3.0.0.  ** file_format==2    Version 3.1.3.  ** file_format==3    Version 3.1.4.  **  ** Version 3.0 can only use files with file_format==1. Version 3.1.3  ** can read and write files with file_format==1 or file_format==2.  ** Version 3.1.4 can read and write file formats 1, 2 and 3.  */  if( meta[1]>3 ){    sqlite3BtreeCloseCursor(curMain);    sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);    return SQLITE_ERROR;  }  sqlite3BtreeSetCacheSize(db->aDb[iDb].pBt, db->aDb[iDb].cache_size);  /* Read the schema information out of the schema tables  */  assert( db->init.busy );  if( rc==SQLITE_EMPTY ){    /* For an empty database, there is nothing to read */    rc = SQLITE_OK;  }else{    char *zSql;    zSql = sqlite3MPrintf(        "SELECT name, rootpage, sql, '%s' FROM '%q'.%s",        zDbNum, db->aDb[iDb].zName, zMasterName);    sqlite3SafetyOff(db);    rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);    sqlite3SafetyOn(db);    sqliteFree(zSql);    sqlite3BtreeCloseCursor(curMain);  }  if( sqlite3_malloc_failed ){    sqlite3SetString(pzErrMsg, "out of memory", (char*)0);    rc = SQLITE_NOMEM;    sqlite3ResetInternalSchema(db, 0);  }  if( rc==SQLITE_OK ){    DbSetProperty(db, iDb, DB_SchemaLoaded);  }else{    sqlite3ResetInternalSchema(db, iDb);  }  return rc;}
开发者ID:huangyt,项目名称:foundations.github.com,代码行数:101,


示例19: main

int main(int argc, char** args){    // Create an int variable for storing the return code for each call    int retval;        // The number of queries to be handled,size of each query and pointer    int q_cnt = 5,q_size = 150,ind = 0;    char **queries = malloc(sizeof(char) * q_cnt * q_size);            // A prepered statement for fetching tables    sqlite3_stmt *stmt;        // Create a handle for database connection, create a pointer to sqlite3    sqlite3 *handle;        // try to create the database. If it doesnt exist, it would be created    // pass a pointer to the pointer to sqlite3, in short sqlite3**    retval = sqlite3_open("sampledb.sqlite3",&handle);    // If connection failed, handle returns NULL    if(retval)    {        printf("Database connection failed/n");        return -1;    }    printf("Connection successful/n");        // Create the SQL query for creating a table    char create_table[100] = "CREATE TABLE IF NOT EXISTS users (uname TEXT PRIMARY KEY,pass TEXT NOT NULL,activated INTEGER)";        // Execute the query for creating the table    retval = sqlite3_exec(handle,create_table,0,0,0);        // Insert first row and second row    queries[ind++] = "INSERT INTO users VALUES('manish','mani',1)";    retval = sqlite3_exec(handle,queries[ind-1],0,0,0);    queries[ind++] = "INSERT INTO users VALUES('mehul','pulsar',0)";    retval = sqlite3_exec(handle,queries[ind-1],0,0,0);        // select those rows from the table    queries[ind++] = "SELECT * from users";    retval = sqlite3_prepare_v2(handle,queries[ind-1],-1,&stmt,0);    if(retval)    {        printf("Selecting data from DB Failed/n");        return -1;    }        // Read the number of rows fetched    int cols = sqlite3_column_count(stmt);            while(1)    {        // fetch a row's status        retval = sqlite3_step(stmt);                if(retval == SQLITE_ROW)        {            // SQLITE_ROW means fetched a row                        // sqlite3_column_text returns a const void* , typecast it to const char*            for(int col=0 ; col<cols;col++)            {                const char *val = (const char*)sqlite3_column_text(stmt,col);                printf("%s = %s/t",sqlite3_column_name(stmt,col),val);            }            printf("/n");        }        else if(retval == SQLITE_DONE)        {            // All rows finished            printf("All rows fetched/n");            break;        }        else        {            // Some error encountered            printf("Some error encountered/n");            return -1;        }    }        // Close the handle to free memory    sqlite3_close(handle);    return 0;}
开发者ID:NavDhaliwal,项目名称:StudentProjects,代码行数:85,


示例20: main

int main(int argc, char **argv) {  sqlite3 *db;  int rc;  int cache_sz = -1;  int page_sz = -1;  char flag;  char *inf, *outf, *key;  char *sql;    while ((flag = getopt(argc, argv, "i:o:k:c:p:")) != -1) {    switch(flag) {      case 'i':        if((inf = (char *)calloc((size_t) strlen(optarg) + 1, sizeof(char))) == NULL) {           ERROR(("no memory"));           exit(1);        }        strcpy(inf, optarg);        break;      case 'o':        if((outf = (char *)calloc((size_t) strlen(optarg) + 1, sizeof(char))) == NULL) {           ERROR(("no memory"));           exit(1);        }        strcpy(outf, optarg);        break;      case 'k':        if((key = (char *) calloc((size_t) strlen(optarg) + 1, sizeof(char))) == NULL) {           ERROR(("no memory"));           exit(1);        }        strcpy(key, optarg);        break;      case 'c':        cache_sz = atoi(optarg);        break;      case 'p':        page_sz = atoi(optarg);        break;      case '?':      default:        break;     }  }  argc -= optind;  argv += optind;  if(inf == NULL || outf == NULL || key == NULL) {    ERROR(("usage: exportencrypt -i <input file> -o <output file> -k <key> [-c cache_size] [-p page_size]/n"));    exit(1);  }  if ((rc = sqlite3_open(inf, &db)) != SQLITE_OK) {     ERROR(("sqlite3_open failed for %s: %d, %s/n", inf, rc, sqlite3_errmsg(db)))  }  if(cache_sz != -1) {    sql = sqlite3_mprintf("PRAGMA cache_size = %d;", cache_sz);     rc = (sql == NULL) ? SQLITE_NOMEM : sqlite3_exec(db, sql, NULL, 0, NULL);     INFO(("%s/n", sql));    if( rc!=SQLITE_OK ) goto end_of_export;    sqlite3_free(sql);  }  sql = sqlite3_mprintf("ATTACH DATABASE %Q AS enc KEY %Q;", outf, key);   rc = (sql == NULL) ? SQLITE_NOMEM : sqlite3_exec(db, sql, NULL, 0, NULL);   INFO(("%s/n", sql));  if( rc!=SQLITE_OK ) goto end_of_export;  sqlite3_free(sql);  if(page_sz != -1) {    sql = sqlite3_mprintf("PRAGMA enc.cipher_page_size = %d;", page_sz);     rc = (sql == NULL) ? SQLITE_NOMEM : sqlite3_exec(db, sql, NULL, 0, NULL);     INFO(("%s/n", sql));    if( rc!=SQLITE_OK ) goto end_of_export;    sqlite3_free(sql);  }    sql = "SELECT sqlcipher_export('enc');";  rc = sqlite3_exec(db, sql, NULL, 0, NULL);   INFO(("%s/n", sql));  if( rc!=SQLITE_OK ) goto end_of_export;  sql = "SELECT sqlcipher_export('enc');";  rc = sqlite3_exec(db, sql, NULL, 0, NULL);   INFO(("%s/n", sql));  if( rc!=SQLITE_OK ) goto end_of_export;  sql = "DETACH DATABASE enc;";  rc = sqlite3_exec(db, sql, NULL, 0, NULL);   INFO(("%s/n", sql));  if( rc!=SQLITE_OK ) goto end_of_export;  sql = NULL;end_of_export:  if(rc != SQLITE_OK) {    ERROR(("error %d: %s/n", rc, sqlite3_errmsg(db)))  }  sqlite3_close(db);//.........这里部分代码省略.........
开发者ID:NextGenIntelligence,项目名称:sqlcipher-tools,代码行数:101,


示例21: batch_add_e3ds

void batch_add_e3ds(char *file_name){    /** public function - see header */    FILE* file;    if((file=fopen(file_name, "r"))==NULL){        log_event(EVENT_ERROR, "file [%s] not found", file_name);        stop_server();    }    char line[160]="";    int line_counter=0;    log_event(EVENT_INITIALISATION, "/nAdding e3ds specified in file [%s]", file_name);    fprintf(stderr, "/nAdding e3ds specified in file [%s]/n", file_name);    //check database is open and table exists    check_db_open(GET_CALL_INFO);    check_table_exists("E3D_TABLE", GET_CALL_INFO);    sqlite3_stmt *stmt;    char *sErrMsg = 0;    char *sql="INSERT INTO E3D_TABLE("  /    "E3D_ID," /    "E3D_FILENAME,"  /    "OBJECT_ID" /    ") VALUES(?, ?, ?)";    prepare_query(sql, &stmt, GET_CALL_INFO);    int rc=sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &sErrMsg);    if(rc!=SQLITE_OK){        log_event(EVENT_ERROR, "sqlite3_exec failed", GET_CALL_INFO);        log_text(EVENT_ERROR, "return code [%i] message [%s] sql [%s]", rc, *&sErrMsg, sql);    }    while (fgets(line, sizeof(line), file)) {        line_counter++;        sscanf(line, "%*s");        char output[5][MAX_LST_LINE_LEN];        memset(&output, 0, sizeof(output));        parse_line(line, output);        sqlite3_bind_int(stmt, 1, atoi(output[0]));                 //e3d id        sqlite3_bind_text(stmt, 2, output[1], -1, SQLITE_STATIC);   //e3d file name        sqlite3_bind_int(stmt, 3, atoi(output[2]));                 //object id        step_query(sql, &stmt, GET_CALL_INFO);        sqlite3_clear_bindings(stmt);        sqlite3_reset(stmt);        fprintf(stderr, "e3d [%s] added successfully/n", output[1]);        log_event(EVENT_SESSION, "Added e3d [%s] to E3D_TABLE", output[1]);    }    rc=sqlite3_exec(db, "END TRANSACTION", NULL, NULL, &sErrMsg);    if (rc!=SQLITE_OK) {        log_event(EVENT_ERROR, "sqlite3_exec failed", GET_CALL_INFO);        log_text(EVENT_ERROR, "return code [%i] message [%s] sql [%s]", rc, *sErrMsg, sql);    }    destroy_query(sql, &stmt, GET_CALL_INFO);    fclose(file);    //load data so it can be used by other functions    load_db_e3ds();    e3ds.data_loaded=true;}
开发者ID:UnoffLandz,项目名称:unoff-landz,代码行数:79,


示例22: SQLI_Unlock

void SQLI_Unlock(struct BE_descs *bed){  if (bed->p->connected) sqlite3_exec(bed->p->desc, unlock_clause, NULL, NULL, NULL);  if (bed->b->connected) sqlite3_exec(bed->b->desc, unlock_clause, NULL, NULL, NULL);}
开发者ID:CodethinkLabs,项目名称:pmacct,代码行数:5,


示例23: dbop3_open

DBOP *dbop3_open(const char *path, int mode, int perm, int flags) {	int rc, rw = 0;	char *errmsg = 0;	DBOP *dbop;	sqlite3 *db3;	const char *tblname;	int cache_size = 0;	STRBUF *sql = strbuf_open_tempbuf();	char buf[1024];	/*	 * When the path is NULL string and private, temporary file is used.	 * The database will be removed when the session is closed.	 */	if (path == NULL) {		path = "";		tblname = "temp";	} else {		/*		 * In case of creation.		 */		if (mode == 1)			(void)truncate(path, 0);		tblname = "db";	}	/*	 * setup arguments.	 */	switch (mode) {	case 0:		rw = SQLITE_OPEN_READONLY;		break;	case 1:		rw = SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;		break;	case 2:		rw = SQLITE_OPEN_READWRITE;		break;	default:		assert(0);	}	/*	 * When the forth argument is NULL, sqlite3_vfs is used.	 */	rc = sqlite3_open_v2(path, &db3, rw, NULL);	if (rc != SQLITE_OK)		die("sqlite3_open_v2 failed. (rc = %d)", rc);	dbop = (DBOP *)check_calloc(sizeof(DBOP), 1);	strlimcpy(dbop->dbname, path, sizeof(dbop->dbname));	dbop->sb        = strbuf_open(0);	dbop->db3       = db3;	dbop->openflags	= flags;	dbop->perm	= (mode == 1) ? perm : 0;	dbop->mode      = mode;	dbop->lastdat	= NULL;	dbop->lastflag	= NULL;	dbop->lastsize	= 0;	dbop->sortout	= NULL;	dbop->sortin	= NULL;	dbop->stmt      = NULL;	dbop->tblname   = check_strdup(tblname);	/*	 * Maximum file size is DBOP_PAGESIZE * 2147483646.	 * if DBOP_PAGESIZE == 8192 then maximum file size is 17592186028032 (17T).	 */	snprintf(buf, sizeof(buf), "pragma page_size=%d", DBOP_PAGESIZE);	rc = sqlite3_exec(dbop->db3, buf,  NULL, NULL, &errmsg);	if (rc != SQLITE_OK)		die("pragma page_size error: %s", errmsg);	/*	 * create table (GTAGS, GRTAGS, GSYMS, GPATH).	 */	if (mode == 1) {		/* drop table */		strbuf_clear(sql);		strbuf_puts(sql, "drop table ");		strbuf_puts(sql, dbop->tblname);		rc = sqlite3_exec(dbop->db3, strbuf_value(sql), NULL, NULL, &errmsg);        	if (rc != SQLITE_OK) {			/* ignore */		}		/* create table */		strbuf_clear(sql);		strbuf_puts(sql, "create table ");		strbuf_puts(sql, dbop->tblname);		strbuf_puts(sql, " (key text, dat text, extra text");		if (!(flags & DBOP_DUP))			strbuf_puts(sql, ", primary key(key)");		strbuf_putc(sql, ')');		rc = sqlite3_exec(dbop->db3, strbuf_value(sql), NULL, NULL, &errmsg);        	if (rc != SQLITE_OK)			die("create table error: %s", errmsg);	}	/*	rc = sqlite3_exec(dbop->db3, "pragma synchronous=off", NULL, NULL, &errmsg);       	if (rc != SQLITE_OK)		die("pragma synchronous=off error: %s", errmsg);	*/	/*//.........这里部分代码省略.........
开发者ID:lianhongHou,项目名称:Emacs,代码行数:101,


示例24: main

int main (int argc, char *argv[]){    sqlite3 *db_handle = NULL;    char *sql_statement;    int ret;    char *err_msg = NULL;    int i;    char **results;    int rows;    int columns;    spatialite_init (0);    ret = sqlite3_open_v2 (":memory:", &db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);    if (ret != SQLITE_OK) {	fprintf (stderr, "cannot open in-memory db: %s/n", sqlite3_errmsg (db_handle));	sqlite3_close (db_handle);	db_handle = NULL;	return -1;    }        ret = sqlite3_exec (db_handle, "create VIRTUAL TABLE dbftest USING VirtualDBF(/"shp/merano-3d/roads.dbf/", 'CP1252');", NULL, NULL, &err_msg);    if (ret != SQLITE_OK) {	fprintf (stderr, "VirtualDBF error: %s/n", err_msg);	sqlite3_free (err_msg);	return -2;    }        ret = sqlite3_exec (db_handle, "DROP TABLE dbftest;", NULL, NULL, &err_msg);    if (ret != SQLITE_OK) {	fprintf (stderr, "DROP TABLE error: %s/n", err_msg);	sqlite3_free (err_msg);	return -3;    }    ret = sqlite3_exec (db_handle, "create VIRTUAL TABLE dbftest USING VirtualDBF('shp/merano-3d/roads.dbf', /"CP1252/");", NULL, NULL, &err_msg);    if (ret != SQLITE_OK) {	fprintf (stderr, "VirtualDBF error: %s/n", err_msg);	sqlite3_free (err_msg);	return -4;    }        ret = sqlite3_exec (db_handle, "DROP TABLE dbftest;", NULL, NULL, &err_msg);    if (ret != SQLITE_OK) {	fprintf (stderr, "DROP TABLE error: %s/n", err_msg);	sqlite3_free (err_msg);	return -5;    }    ret = sqlite3_exec (db_handle, "create VIRTUAL TABLE dbftest USING VirtualDBF('shp/merano-3d/roads.dbf', CP1252);", NULL, NULL, &err_msg);    if (ret != SQLITE_OK) {	fprintf (stderr, "VirtualDBF error: %s/n", err_msg);	sqlite3_free (err_msg);	return -6;    }        for (i = 0; steps[i].sql; ++i) {	ret = sqlite3_get_table (db_handle, steps[i].sql, &results, &rows, &columns, &err_msg);	if (ret != SQLITE_OK) {	    fprintf (stderr, "Error: %s/n", err_msg);	    sqlite3_free (err_msg);	    return -7;	}	if (rows != steps[i].num_rows) {	    fprintf (stderr, "Unexpected num of rows for test %i: %i./n", i, rows);	    return  -8;	}	sqlite3_free_table (results);    }    ret = sqlite3_exec (db_handle, "DROP TABLE dbftest;", NULL, NULL, &err_msg);    if (ret != SQLITE_OK) {	fprintf (stderr, "DROP TABLE error: %s/n", err_msg);	sqlite3_free (err_msg);	return -9;    }    sqlite3_close (db_handle);    spatialite_cleanup();    sqlite3_reset_auto_extension();        return 0;}
开发者ID:stefanklug,项目名称:libspatialite,代码行数:83,


示例25: cache_create_tables

static intcache_create_tables(void){#define T_REPLIES						/  "CREATE TABLE IF NOT EXISTS replies ("			/  "   id                 INTEGER PRIMARY KEY NOT NULL,"		/  "   query              VARCHAR(4096) NOT NULL,"		/  "   reply              BLOB"					/  ");"#define T_QUERIES						/  "CREATE TABLE IF NOT EXISTS queries ("			/  "   id                 INTEGER PRIMARY KEY NOT NULL,"		/  "   query              VARCHAR(4096) UNIQUE NOT NULL,"	/  "   user_agent         VARCHAR(1024),"			/  "   msec               INTEGER DEFAULT 0,"			/  "   timestamp          INTEGER DEFAULT 0"			/  ");"#define I_QUERY							/  "CREATE INDEX IF NOT EXISTS idx_query ON replies (query);"#define T_ARTWORK					/  "CREATE TABLE IF NOT EXISTS artwork ("		/  "   id                  INTEGER PRIMARY KEY NOT NULL,"/  "   persistentid        INTEGER NOT NULL,"		/  "   max_w               INTEGER NOT NULL,"		/  "   max_h               INTEGER NOT NULL,"		/  "   format              INTEGER NOT NULL,"		/  "   filepath            VARCHAR(4096) NOT NULL,"	/  "   db_timestamp        INTEGER DEFAULT 0,"		/  "   data                BLOB"				/  ");"#define I_ARTWORK_ID				/  "CREATE INDEX IF NOT EXISTS idx_persistentidwh ON artwork(persistentid, max_w, max_h);"#define I_ARTWORK_PATH				/  "CREATE INDEX IF NOT EXISTS idx_pathtime ON artwork(filepath, db_timestamp);"#define T_ADMIN_CACHE	/  "CREATE TABLE IF NOT EXISTS admin_cache("	/  " key VARCHAR(32) PRIMARY KEY NOT NULL,"	/  " value VARCHAR(32) NOT NULL"	/  ");"#define Q_CACHE_VERSION	/  "INSERT INTO admin_cache (key, value) VALUES ('cache_version', '%d');"  char *query;  char *errmsg;  int ret;  // Create reply cache table  ret = sqlite3_exec(g_db_hdl, T_REPLIES, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error creating reply cache table: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Create query table (the queries for which we will generate and cache replies)  ret = sqlite3_exec(g_db_hdl, T_QUERIES, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error creating query table: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Create index  ret = sqlite3_exec(g_db_hdl, I_QUERY, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error creating query index: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Create artwork table  ret = sqlite3_exec(g_db_hdl, T_ARTWORK, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error creating artwork table: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Create index  ret = sqlite3_exec(g_db_hdl, I_ARTWORK_ID, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error creating artwork index: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;//.........这里部分代码省略.........
开发者ID:Illuminux,项目名称:forked-daapd,代码行数:101,


示例26: native_setLocale

/* set locale in the android_metadata table, install localized collators, and rebuild indexes */static void native_setLocale(JNIEnv* env, jobject object, jstring localeString, jint flags){    if ((flags & NO_LOCALIZED_COLLATORS)) return;    int err;    char const* locale8 = env->GetStringUTFChars(localeString, NULL);    sqlite3 * handle = (sqlite3 *)env->GetIntField(object, offset_db_handle);    sqlite3_stmt* stmt = NULL;    char** meta = NULL;    int rowCount, colCount;    char* dbLocale = NULL;    // create the table, if necessary and possible    if (!(flags & OPEN_READONLY)) {        static const char *createSql ="CREATE TABLE IF NOT EXISTS " ANDROID_TABLE " (locale TEXT)";        err = sqlite3_exec(handle, createSql, NULL, NULL, NULL);        if (err != SQLITE_OK) {            LOGE("CREATE TABLE " ANDROID_TABLE " failed/n");            throw_sqlite3_exception(env, handle);            goto done;        }    }    // try to read from the table    static const char *selectSql = "SELECT locale FROM " ANDROID_TABLE " LIMIT 1";    err = sqlite3_get_table(handle, selectSql, &meta, &rowCount, &colCount, NULL);    if (err != SQLITE_OK) {        LOGE("SELECT locale FROM " ANDROID_TABLE " failed/n");        throw_sqlite3_exception(env, handle);        goto done;    }    dbLocale = (rowCount >= 1) ? meta[colCount] : NULL;    if (dbLocale != NULL && !strcmp(dbLocale, locale8)) {        // database locale is the same as the desired locale; set up the collators and go        err = register_localized_collators(handle, locale8, UTF16_STORAGE);        if (err != SQLITE_OK) throw_sqlite3_exception(env, handle);        goto done;   // no database changes needed    }    if ((flags & OPEN_READONLY)) {        // read-only database, so we're going to have to put up with whatever we got        // For registering new index. Not for modifing the read-only database.        err = register_localized_collators(handle, locale8, UTF16_STORAGE);        if (err != SQLITE_OK) throw_sqlite3_exception(env, handle);        goto done;    }    // need to update android_metadata and indexes atomically, so use a transaction...    err = sqlite3_exec(handle, "BEGIN TRANSACTION", NULL, NULL, NULL);    if (err != SQLITE_OK) {        LOGE("BEGIN TRANSACTION failed setting locale/n");        throw_sqlite3_exception(env, handle);        goto done;    }    err = register_localized_collators(handle, locale8, UTF16_STORAGE);    if (err != SQLITE_OK) {        LOGE("register_localized_collators() failed setting locale/n");        throw_sqlite3_exception(env, handle);        goto rollback;    }    err = sqlite3_exec(handle, "DELETE FROM " ANDROID_TABLE, NULL, NULL, NULL);    if (err != SQLITE_OK) {        LOGE("DELETE failed setting locale/n");        throw_sqlite3_exception(env, handle);        goto rollback;    }    static const char *sql = "INSERT INTO " ANDROID_TABLE " (locale) VALUES(?);";    err = sqlite3_prepare_v2(handle, sql, -1, &stmt, NULL);    if (err != SQLITE_OK) {        LOGE("sqlite3_prepare_v2(/"%s/") failed/n", sql);        throw_sqlite3_exception(env, handle);        goto rollback;    }    err = sqlite3_bind_text(stmt, 1, locale8, -1, SQLITE_TRANSIENT);    if (err != SQLITE_OK) {        LOGE("sqlite3_bind_text() failed setting locale/n");        throw_sqlite3_exception(env, handle);        goto rollback;    }    err = sqlite3_step(stmt);    if (err != SQLITE_OK && err != SQLITE_DONE) {        LOGE("sqlite3_step(/"%s/") failed setting locale/n", sql);        throw_sqlite3_exception(env, handle);        goto rollback;    }    err = sqlite3_exec(handle, "REINDEX LOCALIZED", NULL, NULL, NULL);    if (err != SQLITE_OK) {        LOGE("REINDEX LOCALIZED failed/n");        throw_sqlite3_exception(env, handle);        goto rollback;    }//.........这里部分代码省略.........
开发者ID:natmal,项目名称:android-database-sqlcipher,代码行数:101,


示例27: cache_drop_tables

static intcache_drop_tables(void){#define D_REPLIES	"DROP TABLE IF EXISTS replies;"#define D_QUERIES	"DROP TABLE IF EXISTS queries;"#define D_QUERY		"DROP INDEX IF EXISTS idx_query;"#define D_ARTWORK	"DROP TABLE IF EXISTS artwork;"#define D_ARTWORK_ID	"DROP INDEX IF EXISTS idx_persistentidwh;"#define D_ARTWORK_PATH	"DROP INDEX IF EXISTS idx_pathtime;"#define D_ADMIN_CACHE	"DROP TABLE IF EXISTS admin_cache;"#define Q_VACUUM	"VACUUM;"  char *errmsg;  int ret;  // Drop reply cache table  ret = sqlite3_exec(g_db_hdl, D_REPLIES, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error dropping reply cache table: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Drop query table  ret = sqlite3_exec(g_db_hdl, D_QUERIES, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error dropping query table: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Drop index  ret = sqlite3_exec(g_db_hdl, D_QUERY, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error dropping query index: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Drop artwork table  ret = sqlite3_exec(g_db_hdl, D_ARTWORK, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error dropping artwork table: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Drop index  ret = sqlite3_exec(g_db_hdl, D_ARTWORK_ID, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error dropping artwork index: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  ret = sqlite3_exec(g_db_hdl, D_ARTWORK_PATH, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error dropping artwork index: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Drop admin cache table  ret = sqlite3_exec(g_db_hdl, D_ADMIN_CACHE, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error dropping admin cache table: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;    }  // Vacuum  ret = sqlite3_exec(g_db_hdl, Q_VACUUM, NULL, NULL, &errmsg);  if (ret != SQLITE_OK)    {      DPRINTF(E_FATAL, L_CACHE, "Error vacuum cache database: %s/n", errmsg);      sqlite3_free(errmsg);      sqlite3_close(g_db_hdl);      return -1;//.........这里部分代码省略.........
开发者ID:Illuminux,项目名称:forked-daapd,代码行数:101,


示例28: main

int main(int argc, char ** argv) {	char * sep;	sqlite3 * db = NULL;	struct Package current = blank_package;	char baseurl[256] = "";	char line[sizeof(current.homepage)]; /* No line will be larger than the largest field */	int code;	int chained_call = 0;	char * db_path = NULL;	/* NOTE: If Package ever contains varible fields, this must be changed */	char sql[sizeof(current) + 8*3*sizeof(char) + 137*sizeof(char) + 256*sizeof(char)];	while((code = getopt(argc, argv, "schd:")) != -1) {		switch(code) {			case 's':				if(db != NULL) {					fputs("-d and -s are mutually exclusive/n", stderr);					exit(EXIT_FAILURE);				}				print_sql = 1;				break;			case 'c':				chained_call = 1;				break;			case 'h':				help();				break;			case 'd':				if(print_sql) {					fputs("-d and -s are mutually exclusive/n", stderr);					exit(EXIT_FAILURE);				}				if(sqlite3_open(optarg, &db) != 0) {					fprintf(stderr, "%s/n", sqlite3_errmsg(db));					exit(EXIT_FAILURE);				}				break;			default:				help();		}	}	/* Open database */	if(!print_sql && db == NULL && (db_path = get_db_path()) && sqlite3_open(db_path, &db) != 0) {		fprintf(stderr, "%s/n", sqlite3_errmsg(db));		exit(EXIT_FAILURE);	}	if(db_path) {		free(db_path);	}	/* Do everything as one transaction. Many times faster */	safe_execute(db, "BEGIN TRANSACTION;");	/* Create tables if they do not exist */	safe_execute(db, "CREATE TABLE IF NOT EXISTS packages " /	                 "(package TEXT PRIMARY KEY, name TEXT, version TEXT," /	                 "maintainer TEXT, installed_size INTEGER, size INTEGER," /	                 "homepage TEXT, section TEXT, category TEXT, baseurl TEXT,"/	                 "path TEXT, md5 TEXT, description TEXT, user_rating INTEGER,"/	                 "user_owns TEXT, status INTEGER, rating INTEGER, price INTEGER);" /	                 "CREATE TABLE IF NOT EXISTS virtual_packages (package TEXT PRIMARY KEY, is_really TEXT);" /	                 "CREATE TABLE IF NOT EXISTS depends (package TEXT, depend TEXT, version TEXT);"	            );	if(!chained_call) {		safe_execute(db, "DELETE FROM virtual_packages;");		safe_execute(db, "DELETE FROM depends;");	}	/* Loop over lines from stream */	code = 0;	while(fgets(line, sizeof(line), stdin)) {		if(line[0] == '#') {			/* Chomp */			if((sep = strchr(line, '/n'))) {				*sep = '/0';			}			strncpy(baseurl, line + 1, sizeof(baseurl)-1);		/* Blank line means end of this package definition */		} else if(line[0] == '/n') {			current.baseurl = baseurl;			if(current.package[0] != '/0') {				package_insert_sql(&current, sql, sizeof(sql));				if(print_sql) {					puts(sql);				} else {					if((code = sqlite3_exec(db, sql, NULL, NULL, NULL)) != 0) {						if(code == SQLITE_CONSTRAINT) {							package_update_sql(&current, sql, sizeof(sql));							safe_execute(db, sql);						} else {							fprintf(stderr, "%s/n", sqlite3_errmsg(db));							exit(EXIT_FAILURE);						}					}				}			}//.........这里部分代码省略.........
开发者ID:psycotica0,项目名称:theveeb-ecosystem,代码行数:101,


示例29: gc_db_init

//.........这里部分代码省略.........  if (creation){    _create_db();  } else {    if ( ! _check_db_integrity() ||	 _gc_boards_count() == 0 )      {	// We failed to load the database, let's	// backup it and re create it.	sqlite3_close(gcompris_db);	gchar *backup = g_strdup_printf("%s.broken", properties->database);	if ( g_rename(properties->database, backup) < 0 )	  {	    // Obviously, we cannot write the backup file either	    g_message("Failed to write the backup database %s", backup);	    disable_database = TRUE;	    return FALSE;	  }	else	  g_message("Database is broken, it is copyed in %s", backup);	g_free(backup);	rc = sqlite3_open(properties->database, &gcompris_db);	if( rc ){	  g_message("Can't open database %s : %s/n", properties->database,		    sqlite3_errmsg(gcompris_db));	  sqlite3_close(gcompris_db);	  disable_database = TRUE;	  return FALSE;	}	_create_db();	if ( ! _check_db_integrity() )	  {	    disable_database = TRUE;	    return FALSE;	  }      }    g_message("Database Integrity ok");    rc = sqlite3_get_table(gcompris_db,			   CHECK_VERSION,			   &result,			   &nrow,			   &ncolumn,			   &zErrMsg			   );    if( rc!=SQLITE_OK ){      g_error("SQL error: %s/n", zErrMsg);    }    if (strcmp(result[1],VERSION)!=0)      g_message("Running GCompris is %s, but database version is %s", VERSION, result[1]);    sqlite3_free_table(result);    /* Schema upgrade */    rc = sqlite3_get_table(gcompris_db,			   PRAGMA_SCHEMA_VERSION,			   &result,			   &nrow,			   &ncolumn,			   &zErrMsg			   );    if( rc!=SQLITE_OK ){      g_error("SQL error: %s/n", zErrMsg);    }    int version = atoi(result[1]);    sqlite3_free_table(result);    if(version <= 16)      {	g_message("Upgrading from <16 schema version/n");	rc = sqlite3_exec(gcompris_db,CREATE_TABLE_LOGS, NULL,  0, &zErrMsg);	if( rc!=SQLITE_OK ) {	  g_error("SQL error: %s/n", zErrMsg);	}      }    if ( _get_user_version() == 0)      {	g_message("Upgrading schema based on user version = 0/n");	rc = sqlite3_exec(gcompris_db,"DROP TABLE boards;", NULL,  0, &zErrMsg);	if( rc!=SQLITE_OK ) {	  g_error("SQL error: %s/n", zErrMsg);	}	rc = sqlite3_exec(gcompris_db,CREATE_TABLE_BOARDS, NULL,  0, &zErrMsg);	if( rc!=SQLITE_OK ) {	  g_error("SQL error: %s/n", zErrMsg);	}	// We just dropped the boards table, force a reread	properties->reread_menu = TRUE;	_set_user_version(1);      }  }  return TRUE;#else  return FALSE;#endif}
开发者ID:GNOME,项目名称:gcompris,代码行数:101,



注:本文中的sqlite3_exec函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ sqlite3_free函数代码示例
C++ sqlite3_errstr函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。