Ejemplo n.º 1
0
Archivo: db.c Proyecto: phedders/zabbix
/* in db.h - #define DBfree_result   SQ_DBfree_result */
void	SQ_DBfree_result(DB_RESULT result)
{
	if(!result) return;

	if(result->data)
	{
		sqlite3_free_table(result->data);
	}

	zbx_free(result);
}
Ejemplo n.º 2
0
listdata*
DatabaseSqlite::create_region_list(int country_id)
{
    listdata *list = NULL;
    int rc;
    char *errMsg = NULL;
    char **result;
    int nrow, ncol;
    //std::string sql;
    char sql[256];
#ifdef DEBUGFUNCTIONCALL
    START_FUNCTION;
#endif
    list = new listdata;
    if(!db){
        return NULL;
    }

    if (country_id == 0 || country_id == -1) return list;

    if(country_id == 0) /* for GPS */
        snprintf(sql, sizeof(sql) - 1,
                 "SELECT id, name FROM regions");
    else {

        snprintf(sql,
                 sizeof(sql) - 1,
                 "SELECT id, name FROM regions WHERE country_id = %d ORDER BY name",
                 country_id);
    }
/*    std::cerr <<"Select region: "<< sql << std::endl; */
    rc = sqlite3_get_table(db,
                           sql,
                           &result,
                           &nrow,
                           &ncol,
                           &errMsg);
    if(rc != SQLITE_OK){
#ifndef RELEASE
        std::cerr << errMsg << std::endl;
#endif
        sqlite3_free(errMsg);
        return NULL;
    }
    for (int i=0; i<ncol*nrow; i=i+2)
        list->push_back(std::make_pair(result[ncol+i], result[ncol+i+1]));

    sqlite3_free_table(result);

#ifdef DEBUGFUNCTIONCALL
    END_FUNCTION;
#endif
    return list;
}
Ejemplo n.º 3
0
int read_init_status(char *init_status_array)
{
	int ret=0;
	char array[2];
	int i,j,id;
	int status_sign[11];
	for(i=0;i<10;i++)
	{
		status_sign[i]=0;
	}
	int result;
	char **dbResult; // ��char **���ͣ�����*��
	int nrow, nColumn,index;
	char* errmsg=NULL;
	
	char read_status_sql[200] = "select id,ipc_status from video_conf order by id";//��id����ȡ��id��ipc_status
	result = sqlite3_get_table(db,read_status_sql, &dbResult, &nrow, &nColumn, &errmsg );
	if(SQLITE_OK == result)
	{
		index = nColumn;
		for(j=0;j<nrow;j++)
	    {
			id = atoi(dbResult[index]);
			for(i=0;i<MAX_IPC_NUM;i++)  // �ҳ����ĸ�IPC
			{
				if(i == id)
				{
					strcpy(array,dbResult[index+1]);
					array[1]='\0';
					status_sign[i]=1;
					init_status_array[i]=array[0];
					continue;
				 }

			}
			index += nColumn;
		}
		for(i=0;i<MAX_IPC_NUM;i++)
		{
			if(status_sign[i]==0)
			{
				init_status_array[i]='c';
			}
		}
		init_status_array[MAX_IPC_NUM]='\0';
	}
	else
	{
		ret=-1;
	}
	sqlite3_free(errmsg);
	sqlite3_free_table(dbResult);
	return ret;
}
Ejemplo n.º 4
0
int update_file_mod_time(char *filename)
{
    struct stat filestat;
    int fileexists;
    fileexists = stat(filename, &filestat);
    if(fileexists<0)
    {
        return -1;
    }
    
    char **resultp=NULL;
    int rows,cols;
    
    char *temp=sqlite3_mprintf("SELECT mod_time FROM files WHERE filename = \'%q\'",filename);
    if(sqlite3_get_table(madshelf_database,temp,&resultp,&rows,&cols,NULL)!=SQLITE_OK)
    {
        sqlite3_free(temp);
        sqlite3_free_table(resultp);    
        return -1;
    }
    else
    {
        sqlite3_free(temp);
    }
    
    if(rows==0)
    {
        temp=sqlite3_mprintf("INSERT INTO files (filename,mod_time) VALUES(\'%q\',%d)",filename,filestat.st_mtime);
        sqlite3_exec(madshelf_database,temp,NULL,NULL,NULL);
        sqlite3_free(temp);
        
    }
    else
    {
        temp=sqlite3_mprintf("UPDATE files SET mod_time=%d WHERE filename=\'%q\'",filestat.st_mtime,filename);
        sqlite3_exec(madshelf_database,temp,NULL,NULL,NULL);
        sqlite3_free(temp);
    }
    sqlite3_free_table(resultp);
    return 0;
}
Ejemplo n.º 5
0
void test_sqlite1(void * pParam)
{
    sqlite3 * db = NULL; // 声明sqlite 关键结构指针
    s32 result;
    char * errmsg = NULL;

    char **dbResult; // 是 char ** 类型,两个* 号
    s32 nRow, nColumn;
    s32 i , j;
    s32 index;
    result = sqlite3_open( "yongshao\\db.db", &db );

    if( result != SQLITE_OK ) {
        printf("open sys:\\yongshao\\db.db error!!!!\n");
    }
    else {
        printf("open sys:\\yongshao\\db.db success!!!!\n");

        // 开始查询数据库 (回调方法)
        //result = sqlite3_exec( db,"select * from MyTable_1", LoadMyInfo, NULL, errmsg );
        //()
        result = sqlite3_get_table ( db,"select * from MyTable_1", &dbResult, &nRow, &nColumn, &errmsg );
        if( SQLITE_OK == result )
        {
            // 查询成功
            index = nColumn;
            printf("查到%d 条记录\n ", nRow );
            for( i = 0; i < nRow ; i++ )
            {
                printf("第 %d 条记录\n", i+1 );
                for( j = 0 ; j < nColumn; j++ )
                {
                    printf("字段名:%s ? > 字段值:%s\n", dbResult[j], dbResult [index] );
                    ++index;
                }
                printf("-------\n");
            }
        }
        else{
            result = sqlite3_exec( db,"create table MyTable_1( ID integer primary key autoincrement, name nvarchar(32) )" , NULL, NULL, &errmsg );
            if(result != SQLITE_OK )
                printf("创建表失败,错误码:%d ,错误原因:%s\n " , result, errmsg );

        }
        // 插入一条记录
        result = sqlite3_exec( db, " insert into MyTable_1( name ) values ( '走路')" , 0, 0, &errmsg );
        if(result != SQLITE_OK )
            printf("插入记录失败,错误码:%d ,错误原因:%s\n" , result, &errmsg );
        sqlite3_free_table ( dbResult );
        sqlite3_close( db );
        printf("close sys:\\yongshao\\db.db !!!!\n");
    }
}
Ejemplo n.º 6
0
int osync_db_count(OSyncDB *db, const char *query, OSyncError **error)
{
	int num;
	char **result = NULL;
	char *errmsg = NULL;
	osync_trace(TRACE_ENTRY, "%s(%p, %s, %p)", __func__, db, query, error);	
	osync_assert(db);
	osync_assert(query);

	if (sqlite3_get_table(db->sqlite3db, query, &result, &num, NULL, &errmsg) != SQLITE_OK) {
		osync_error_set(error, OSYNC_ERROR_GENERIC, "Unable count result of query: %s", errmsg);
		sqlite3_free_table(result);
		sqlite3_free(errmsg);
		osync_trace(TRACE_EXIT_ERROR, "%s: %s", __func__, osync_error_print(error));
		return -1;
	}

	sqlite3_free_table(result);
	osync_trace(TRACE_EXIT, "%s: %i", __func__, num);
	return num;
}
Ejemplo n.º 7
0
void
rsdb_exec_fetch_end(struct rsdb_table *table)
{
    int i;

    for(i = 0; i < table->row_count; i++) {
        rb_free(table->row[i]);
    }
    rb_free(table->row);

    sqlite3_free_table((char **)table->arg);
}
Ejemplo n.º 8
0
int fbSQL::query(string& cmd)
{
	int ret = 0;
	char* errmsg;
	char** result;

	if(db == NULL)
	{
		errlog->warn(FAILEDTOOPENDB, "fbSQL: Query on non-opened database");
		return -1;
	}

	// lock so two commands can't be sent at once
	fbLock lock(cs);
	errlog->debug(NONE, "fbSQL: Query Locked");
	qCS.lock();   /// < lock query

	// send command
	//ret = sqlite3_exec(db, command, callback, 0 , &errmsg);
	ret = sqlite3_get_table(db, cmd.c_str(), &result, &_rows, &_cols, &errmsg);

	// test if okay
	if(ret != SQLITE_OK)
	{	//error, report warning
		errlog->warn(SQLEXECERROR, "fbSQL: sqlite3 error code: %s", errmsg);
		sqlite3_free(errmsg);
		return ret;
	}

	errlog->debug(NONE, "fbSQL: found %d rows with %d cols",  _rows, _cols);


	//clear vectors
	if(col_header.size() != 0) col_header.clear();
	if(table.size() != 0) table.clear();

	//save header information
	for(int i = 0; i < _cols; ++i)
		col_header.push_back(result[i]);

	//save data
	for(int i = 0; i < _cols*_rows; ++i)
		if(result[_cols+i] != NULL)
			table.push_back(result[_cols+i]);
		else
			table.push_back("");

	errlog->debug(NONE, "fbSQL: Filled Table data: %d", (int)table.size());

	sqlite3_free_table(result);
	errlog->debug(NONE, "fbSQL: Query OK");
	return ret;
}
Ejemplo n.º 9
0
void DatabaseSqlite::get_station_coordinate(std::string code, double &latitude, double &longitude)
{
    char sql[256];
    int rc;
    char *errMsg = NULL;
    char **result;
    int nrow, ncol;

#ifdef DEBUGFUNCTIONCALL
    START_FUNCTION;
#endif
    if (!db)
        return; /* database doesn't open */
    std::cerr << "in get station coordinate " << code << std::endl;
    snprintf(sql,
             sizeof(sql) - 1,
             "select latitude, longititude from stations where code='%s'",
             code.c_str());
    std::cerr << "sql = " << sql << std::endl;

    rc = sqlite3_get_table(db,
                           sql,
                           &result,
                           &nrow,
                           &ncol,
                           &errMsg);

    //rc = sqlite3_exec(db, sql, callback, 0, &errMsg);
    if(rc != SQLITE_OK){
#ifndef RELEASE
        std::cerr << errMsg << std::endl;
#endif
        sqlite3_free(errMsg);
        latitude = -1;
        longitude = -1;
        return;
    }
    if (nrow == 0){
        latitude = -1;
        longitude = -1;
        return;
    }

    latitude = atof(result[ncol+0]);
    longitude = atof(result[ncol+1]);

    sqlite3_free_table(result);

#ifdef DEBUGFUNCTIONCALL
    END_FUNCTION;
#endif
}
Ejemplo n.º 10
0
	HawkSqlite::QueryResult::~QueryResult()
	{
		if (m_pRes)
		{
			//清理结果集
			sqlite3_free_table((Char**)m_pRes);			

			//数据重置
			m_iRow = 0;
			m_iCol = 0;
			m_pRes = 0;
		}
	}	
Ejemplo n.º 11
0
void db_close_table(void)
{
    if (tablep)
        sqlite3_free_table(tablep);
    else
        g_print("ERROR: TABLE CLOSED TWICE!\n");
    tablep = NULL;
#if (GTKVER == 3)
    G_UNLOCK(table_mutex);
#else
    g_static_mutex_unlock(&table_mutex);
#endif
}
Ejemplo n.º 12
0
int
_sqlite_drv_get_spamtotals (DSPAM_CTX * CTX)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  char query[1024];
  char *err=NULL, **row;
  int nrow, ncolumn;
  int rc;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_sqlite_drv_get_spamtotals: invalid database handle (NULL)");
    return EINVAL;
  }

  memset(&s->control_totals, 0, sizeof(struct _ds_spam_totals));
  memset(&CTX->totals, 0, sizeof(struct _ds_spam_totals));

  snprintf (query, sizeof (query),
            "select spam_learned, innocent_learned, "
            "spam_misclassified, innocent_misclassified, "
            "spam_corpusfed, innocent_corpusfed, "
            "spam_classified, innocent_classified "
            " from dspam_stats");

  if ((sqlite3_get_table(s->dbh, query, &row, &nrow, &ncolumn, &err))!=SQLITE_OK)
  {
    _sqlite_drv_query_error (err, query);
    return EFAILURE;
  }

  if (nrow>0 && row != NULL) {
    CTX->totals.spam_learned		= strtol (row[ncolumn], NULL, 0);
    CTX->totals.innocent_learned	= strtol (row[ncolumn+1], NULL, 0);
    CTX->totals.spam_misclassified	= strtol (row[ncolumn+2], NULL, 0);
    CTX->totals.innocent_misclassified 	= strtol (row[ncolumn+3], NULL, 0);
    CTX->totals.spam_corpusfed		= strtol (row[ncolumn+4], NULL, 0);
    CTX->totals.innocent_corpusfed	= strtol (row[ncolumn+5], NULL, 0);
    CTX->totals.spam_classified		= strtol (row[ncolumn+6], NULL, 0);
    CTX->totals.innocent_classified	= strtol (row[ncolumn+7], NULL, 0);
    rc = 0;
  } else {
    rc = EFAILURE;
  }

  sqlite3_free_table(row);
  if ( !rc )
    memcpy(&s->control_totals, &CTX->totals, sizeof(struct _ds_spam_totals));

  return rc;
}
Ejemplo n.º 13
0
bool get_peerProfileById(const char *uid, char **nick_name, char **group_name, int *sex, int *age, char **introduction, char **head_image_path, int *server_id, char **server_uid, char **last_ip, int *tcp_port, int *udp_port)
{
	int nrows,ncols; //nrows:记录返回数据库表的行数,ncols:记录返回表的列数
	char *errmsg=0;//记录返回的错误信息。
	char **results;//记录返回的查询结果
	sqlite3 *db=0; //记录返回的数据库句柄

	if(!open_db(&db, PEERSINFO_DBFILE_NAME))
		return false;

	//下述函数进行查询数据库操作
	char *szBaseSql = "select * from peers_profile where uid='";
	char *szSql = v6strcat(3, szBaseSql, uid, "';");
	int rc=sqlite3_get_table(db,szSql,&results,&nrows,&ncols,&errmsg);
	release_db_data((void **)&szSql);
	CHECK_RC(rc,errmsg,db);

	bool success = true;
	if(nrows > 0)
	{
		int buf_size = strlen(results[PEERSINFO_DB_ROWS+1])+1;
		*nick_name  = (char*)malloc(buf_size);
		memcpy(*nick_name, results[PEERSINFO_DB_ROWS+1], buf_size);
		buf_size = strlen(results[PEERSINFO_DB_ROWS+2])+1;
		*group_name  = (char*)malloc(buf_size);
		memcpy(*group_name, results[PEERSINFO_DB_ROWS+2], buf_size);
	    *sex = atoi(results[PEERSINFO_DB_ROWS+3]);
		*age = atoi(results[PEERSINFO_DB_ROWS+4]);
		buf_size = strlen(results[PEERSINFO_DB_ROWS+5])+1;
		*introduction = (char*)malloc(buf_size);
		memcpy(*introduction, results[PEERSINFO_DB_ROWS+5], buf_size);
		buf_size = strlen(results[PEERSINFO_DB_ROWS+6])+1;
		*head_image_path = (char*)malloc(buf_size);
		memcpy(*head_image_path, results[PEERSINFO_DB_ROWS+6], buf_size);
		*server_id = atoi(results[PEERSINFO_DB_ROWS+7]);
		buf_size = strlen(results[PEERSINFO_DB_ROWS+8])+1;
		*server_uid = (char*)malloc(buf_size);
		memcpy(*server_uid, results[PEERSINFO_DB_ROWS+8], buf_size);
		buf_size = strlen(results[PEERSINFO_DB_ROWS+9])+1;
		*last_ip = (char*)malloc(buf_size);
		memcpy(*last_ip, results[PEERSINFO_DB_ROWS+9], buf_size);
		*tcp_port = atoi(results[PEERSINFO_DB_ROWS+10]);
		*udp_port = atoi(results[PEERSINFO_DB_ROWS+11]);
	}
	else
		success = false;

	sqlite3_free_table(results);
	sqlite3_close(db);
	return success;
}
Ejemplo n.º 14
0
static int __count_with_field(const char *tbl_name, const char *f_name,
			     const char *val, int equal)
{
	char tmp_val[BUF_MAX_LEN];
	char *_sqlbuf;
	int rc;
	char **db_result = NULL;
	char *db_err = NULL;
	int nrows = 0;
	int ncols = 0;
	int cnt;

	if (equal) {
		_sqlbuf = sqlite3_mprintf(
				"SELECT COUNT(*) FROM %s WHERE %s = '%s';",
				tbl_name, f_name, val);
	} else {
		snprintf(tmp_val, BUF_MAX_LEN, "%%%s%%", val);
		_sqlbuf = sqlite3_mprintf(
		"SELECT COUNT(*) FROM %s WHERE %s like '%s';", tbl_name,
		f_name, tmp_val);
	}

	rc = sqlite3_get_table(mida_db, _sqlbuf, &db_result, &nrows, &ncols,
			       &db_err);
	if (rc == -1 || nrows == 0) {
		_D("get count = 0 or fail");
		sqlite3_free_table(db_result);
		sqlite3_free(_sqlbuf);
		return 0;
	} else {
		cnt = atoi(db_result[1]);
		sqlite3_free_table(db_result);
		sqlite3_free(_sqlbuf);
	}

	return cnt;
}
Ejemplo n.º 15
0
static tb_void_t tb_database_sqlite3_clos(tb_database_sql_impl_t* database)
{
    // check
    tb_database_sqlite3_t* sqlite = tb_database_sqlite3_cast(database);
    tb_assert_and_check_return(sqlite);
    
    // exit result first if exists
    if (sqlite->result.result) sqlite3_free_table(sqlite->result.result);
    sqlite->result.result = tb_null;

    // close database
    if (sqlite->database) sqlite3_close(sqlite->database);
    sqlite->database = tb_null;
}
Ejemplo n.º 16
0
/*
  Highscore-keeping class
*/
Highscore::Highscore()
{
  // TODO: Open and load score database
  int result = sqlite3_open("highscores.db", &db);
  if (result != SQLITE_OK)
  {
    printf("Highscore::Highscore(): Failed to open score database in 'highscores.db'! Highscore table will be empty.\n");
    printf("Error was:\n%s\n", sqlite3_errmsg(db));
    sqlite3_close(db);
    db = NULL;
  }
  else
  {
    char* error_msg = NULL;
    result = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS Highscores { scoreID INTEGER PRIMARY KEY, scoreNumber INTEGER, scoreName TEXT, scoreDate TEXT };", NULL, NULL, &error_msg);
    if (result != SQLITE_OK)
    {
      printf("Highscore::Highscore(): Failed to create highscore table in database file 'highscores.db'. Highscore table will be empty.\n");
      printf("Error was:\n%s\n", error_msg);
      sqlite3_free(error_msg);
      sqlite3_close(db);
      db = NULL;
    }
    
    {
      char** results;
      int numRows, numCols;
      result = sqlite3_get_table(db, "SELECT scoreID, scoreNumber, scoreName, scoreDate FROM Highscores ORDER BY scoreNumber;", &results, &numRows, &numCols, &error_msg);
      
      int indexID=0, indexNumber=1, indexName=2, indexDate=3;
      for (int i=0; i < numCols; i++)
      {
        if (strcmp(results[i], "scoreID") == 0)  indexID = i;
        else if (strcmp(results[i], "scoreNumber") == 0)  indexNumber = i;
        else if (strcmp(results[i], "scoreName") == 0)  indexName = i;
        else if (strcmp(results[i], "scoreDate") == 0)  indexDate = i;
      }
      // Process the table data
      for (int row=0; row < numRows; row++)
      {
        HighscoreEntry e(atol(results[numRows*(1+row)+indexNumber]),
                              string(results[numRows*(1+row)+indexName]),
                              string(results[numRows*(1+row)+indexDate]));
        insertEntry(e);
      }
      
      sqlite3_free_table(results);
    }
  }
} // end Highscore() constructor
Ejemplo n.º 17
0
long get_file_index(char *filename,int create_entry_if_missing)
{
    
    char **resultp=NULL;
    int rows,cols;
    char *temp=sqlite3_mprintf("SELECT fileid FROM files WHERE filename = \'%q\'",filename);
    int result= sqlite3_get_table(madshelf_database,temp,&resultp,&rows,&cols,NULL);
    sqlite3_free(temp);
    if(rows<=0 && create_entry_if_missing)
    {
        struct stat filestat;
        int fileexists;
        fileexists = stat(filename, &filestat);
        if(fileexists<0)
        {
            return -1;
        }
        
        sqlite3_free_table(resultp);
        temp=sqlite3_mprintf("INSERT INTO files (filename,mod_time) VALUES(\'%q\',%d)",filename,filestat.st_mtime);
        sqlite3_exec(madshelf_database,temp,NULL,NULL,NULL);
        sqlite3_free(temp);
        char *temp=sqlite3_mprintf("SELECT fileid FROM files WHERE filename = \'%q\'",filename);
        result= sqlite3_get_table(madshelf_database,temp,&resultp,&rows,&cols,NULL);
        sqlite3_free(temp);

    }
    if(rows<=0)
    {
        sqlite3_free_table(resultp);
        return -1;
    }
    
    long retval=strtol(resultp[cols],NULL,10);
    sqlite3_free_table(resultp);
    return retval;
}
Ejemplo n.º 18
0
std::vector<Cookie> SqliteWrapper::printCookies(const char *filename, int mode)
{
    std::vector<Cookie> c;

    int rc;
	char *error;

	sqlite3 *db;
	rc = sqlite3_open(filename, &db);
	if (rc)
	{
		std::cerr << "Error opening SQLite3 database: " << sqlite3_errmsg(db) << std::endl << std::endl;
		sqlite3_close(db);
		return c;
	}

    const char *sqlSelect;

    if ( mode == 1)
        sqlSelect = "SELECT name, value, expiry FROM moz_cookies;";

    else if ( mode ==2 )
        sqlSelect = "SELECT name, value, expires_utc FROM cookies;";

	char **results = NULL;
	int rows, columns;
	sqlite3_get_table(db, sqlSelect, &results, &rows, &columns, &error);
	if (rc)
	{
		std::cerr << "Error executing SQLite3 query: " << sqlite3_errmsg(db) << std::endl << std::endl;
		sqlite3_free(error);
	}
	else
	{
		for (int rowCtr = 0; rowCtr <= rows; ++rowCtr)
		{
		    std::string a[3];
			for (int colCtr = 0; colCtr < columns; ++colCtr)
			{
				int cellPosition = (rowCtr * columns) + colCtr;
				a[colCtr] = results[cellPosition];
			}

			c.push_back(Cookie(a[0], a[1],a[2]));
		}
	}
	sqlite3_free_table(results);
	sqlite3_close(db);
}
Ejemplo n.º 19
0
bool QgsSpatiaLiteSourceSelect::isDeclaredHidden( sqlite3 * handle, QString table, QString geom )
{
  int ret;
  int i;
  char **results;
  int rows;
  int columns;
  char *errMsg = NULL;
  bool isHidden = false;

  if ( !checkGeometryColumnsAuth( handle ) )
    return false;
  // checking if some Layer has been declared as HIDDEN
  QString sql = QString( "SELECT hidden FROM geometry_columns_auth"
                         " WHERE f_table_name=%1 and f_geometry_column=%2" ).arg( quotedValue( table ) ).
                arg( quotedValue( geom ) );

  ret = sqlite3_get_table( handle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );
  if ( ret != SQLITE_OK )
    goto error;
  if ( rows < 1 )
    ;
  else
  {
    for ( i = 1; i <= rows; i++ )
    {
      if ( results[( i * columns ) + 0] != NULL )
      {
        if ( atoi( results[( i * columns ) + 0] ) != 0 )
          isHidden = true;
      }
    }
  }
  sqlite3_free_table( results );

  return isHidden;

error:
  // unexpected IO error
  QString errCause = tr( "unknown error cause" );
  if ( errMsg != NULL )
  {
    errCause = errMsg;
    sqlite3_free( errMsg );
  }
  QMessageBox::critical( this, tr( "SpatiaLite getTableInfo Error" ),
                         tr( "Failure exploring tables from: %1\n\n%2" ).arg( mSqlitePath ).arg( errCause ) );
  return false;
}
Ejemplo n.º 20
0
static bool _hasCache( sqlite3* db, const QString& connName, int flags = -1 ) // flags == -1 implies any flags
{
  QString sqlCacheForConn = QString( "SELECT * FROM meta_oracle WHERE conn = %1" ).arg( QgsOracleConn::quotedValue( connName ) );
  if ( flags >= 0 )
    sqlCacheForConn.append( QString( " AND flags = %1" ).arg( flags ) );

  char **results;
  int rows, columns;
  char *errMsg = nullptr;
  bool res = sqlite3_get_table( db, sqlCacheForConn.toUtf8(), &results, &rows, &columns, &errMsg ) == SQLITE_OK;
  bool hasCache = ( res && rows == 1 );
  sqlite3_free_table( results );

  return hasCache;
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
	cgi_init();
	cgi_session_start();
	cgi_process_form();
	cgi_init_headers();

	sqlite3 *db;
	char *err = 0;
	char *sql = NULL;
	char **result=NULL;
	int row=0,col=0;
	int ret = 0;
	ret = sqlite3_open(DATEBASE,&db);
	if(ret != SQLITE_OK)
	{
		fputs(sqlite3_errmsg(db),stderr);
		fputs("\n",stderr);
		exit(1);
	}
	sql = sqlite3_mprintf("select U_prim from UserInfo where U_id='%s' and U_pwd='%s'",
						  cgi_param("user"),cgi_param("password"));
	ret = sqlite3_get_table(db,sql,&result,&row,&col,&err);
	if(ret != SQLITE_OK)
	{
		fputs(err,stderr);
		fputs("\n",stderr);
		sqlite3_close(db);
		exit(1);
	}
	if(col == 0 && row == 0)
	{
		/* 修改路径 */
		printf("bad input");
		printf("%s  ",cgi_param("user"));
		cgi_include ("../htdocs/login.html");
	}
	else
	{
		cgi_session_register_var("logged",result[1]);
		/* 修改系统用户跳转页面地址 */
		cgi_include("../htdocs/main.html");	
	}
	sqlite3_free_table(result);
	sqlite3_close(db);
	cgi_end();
	return 0;
}
Ejemplo n.º 22
0
///========return a struct with the dl manager related data==========================///
std::vector <dl_mngr>
config::db_get_dl_managers()
{
	std::vector <dl_mngr> container;
	dl_mngr temp_list;
	char **pazResult;
	int row, column;

	rc = sqlite3_get_table(
		db,                        /* An open database */
		"select * from dl_managers;",/* SQL to be evaluated */
		&pazResult,                /* Results of the query */
		&row,                      /* Number of result rows written here */
		&column,                   /* Number of result columns written here */
		&zErrMsg                   /* Error msg written here */
	);

	if ( rc!=SQLITE_OK ) {
		std::cerr<< "SQL error: "<< zErrMsg <<"\n";
		sqlite3_free(zErrMsg);
		zErrMsg = 0;
	}
	else {
		for (int i = 0, k = 3; i<row; i++, k+=3) {
			pazResult[i+k] ? (temp_list.name = pazResult[i+k]): (temp_list.name="");
			pazResult[i+k+1] ? (temp_list.command = pazResult[i+k+1]): (temp_list.command="");
			if (pazResult[i+k+2]) {
				if (strcmp(pazResult[i+k+2], "1") == 0) {
					 temp_list.selected = true;
				}
				else  {
					temp_list.selected = false;
				}
			}
			else {
				temp_list.selected = false;
			}
			if (temp_list.name!="") {
				container.push_back(temp_list);
			}
			else {
			}
			k--;
		}
		sqlite3_free_table(pazResult);
	}
	return container;
}
Ejemplo n.º 23
0
BOOL isUserMobileNumberValid(const char *mobile_number)
{
	int row_num = 0,column_num = 0;
	char sql[1024] = {0};
	char **azResult;
	if(database_open()==FALSE) return FALSE;
	sprintf(sql,"select * from alarmtable where F_TYPE='mobile' and F_VALUE='%s' and F_STATE='o'",mobile_number);
	sqlite3_get_table(db_user,sql,  &azResult, &row_num, &column_num, NULL);
	if(row_num>0){
		sqlite3_free_table(azResult);
		database_close();
		return TRUE;
	}
	database_close();
	return FALSE;
}
Ejemplo n.º 24
0
void VersionTable::fetchVersion()
{
	char **re;
	int nRow, nColumn;
		
	sqlite3_get_table(InitDatabase::getInstance()->getDatabseSqlite(), "select * from Versions  limit 1", &re, &nRow, &nColumn,NULL);

	if (nRow > 0)
	{
		m_VersionInfo.iVersionId = int(strtod(re[nColumn+0], 0));
		m_VersionInfo.iVersionSync = int(strtod(re[nColumn+1], 0));
		m_VersionInfo.iVersionDatabase = int(strtod(re[nColumn+2], 0));
	}

	sqlite3_free_table(re);
}
Ejemplo n.º 25
0
  void print_sqlite_table(sqlite3 *db, string tablename) {
    fprintf(stdout, "Printing table: %s.  ", tablename.c_str());
    string sql = "SELECT * FROM " + tablename;
    int rc, nr, nc, size;
    char **table;
    rc = sqlite3_get_table(db, sql.c_str(), &table, &nr, &nc, 0);
    fprintf(stdout, "There are %d rows.\n", nr);    
    size = (nr * nc) + nc;
    for(int i=0; i<size; i++) {
      fprintf(stdout, "%s\t", table[i]);
      if(((i+1) % nc) == 0) 
	fprintf(stdout, "\n");
    }
    fprintf(stdout, "\n");
    sqlite3_free_table(table);
  };
Ejemplo n.º 26
0
bool QgsSpatiaLiteConnection::isDeclaredHidden( sqlite3 *handle, const QString &table, const QString &geom )
{
  int ret;
  int i;
  char **results = nullptr;
  int rows;
  int columns;
  char *errMsg = nullptr;
  bool isHidden = false;

  if ( !checkGeometryColumnsAuth( handle ) )
    return false;
  // checking if some Layer has been declared as HIDDEN
  QString sql = QString( "SELECT hidden FROM geometry_columns_auth"
                         " WHERE f_table_name=%1 and f_geometry_column=%2" ).arg( quotedValue( table ),
                             quotedValue( geom ) );

  ret = sqlite3_get_table( handle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );
  if ( ret != SQLITE_OK )
    goto error;
  if ( rows < 1 )
    ;
  else
  {
    for ( i = 1; i <= rows; i++ )
    {
      if ( results[( i * columns ) + 0] )
      {
        if ( atoi( results[( i * columns ) + 0] ) != 0 )
          isHidden = true;
      }
    }
  }
  sqlite3_free_table( results );

  return isHidden;

error:
  // unexpected IO error
  mErrorMsg = tr( "unknown error cause" );
  if ( errMsg )
  {
    mErrorMsg = errMsg;
    sqlite3_free( errMsg );
  }
  return false;
}
Ejemplo n.º 27
0
int main()
{
    int rc;

    rc = sqlite3_open("test.db",&db);
    rc = sqlite3_exec(db,"create table stu (id integer primary key,name text,sex text,key integer)",0,0,&errmsg);
    rc = sqlite3_exec(db,"insert into stu values('4','dab','male',24)",0,0,&errmsg);

    if(rc)
    {
        printf("not open datebase!\n");
    }
    else
    {
        printf("exec success!\n");   
    }

    int i;
    int j;
    int nrow;
    int ncolumn;

    rc = sqlite3_get_table(db,"select * from stu",&result,&nrow,&ncolumn,&errmsg);
   
    if(rc)
    {
        printf("query fail!\n");
    }
    else
    {
        for(i = 1; i <= nrow ;i++)
        {
            for(j = 0; j <= ncolumn; j++)
            {
                printf("%5s |",result[i*ncolumn + j]);
            }

            printf("\n");
        }
    }

    sqlite3_free_table(result);

    sqlite3_close(db);

    return 0;
}
Ejemplo n.º 28
0
GIntBig OGRSQLiteSelectLayerCommonBehaviour::GetFeatureCount( int bForce )
{
    if( bEmptyLayer )
        return 0;

    if( poLayer->GetFeatureQuery() == NULL &&
        STARTS_WITH_CI(osSQLCurrent, "SELECT COUNT(*) FROM") &&
        osSQLCurrent.ifind(" GROUP BY ") == std::string::npos &&
        osSQLCurrent.ifind(" UNION ") == std::string::npos &&
        osSQLCurrent.ifind(" INTERSECT ") == std::string::npos &&
        osSQLCurrent.ifind(" EXCEPT ") == std::string::npos )
        return 1;

    if( poLayer->GetFeatureQuery() != NULL || (poLayer->GetFilterGeom() != NULL && !bSpatialFilterInSQL) )
        return poLayer->BaseGetFeatureCount(bForce);

    CPLString osFeatureCountSQL("SELECT COUNT(*) FROM (");
    osFeatureCountSQL += osSQLCurrent;
    osFeatureCountSQL += ")";

    CPLDebug("SQLITE", "Running %s", osFeatureCountSQL.c_str());

/* -------------------------------------------------------------------- */
/*      Execute.                                                        */
/* -------------------------------------------------------------------- */
    char *pszErrMsg = NULL;
    char **papszResult;
    int nRowCount, nColCount;
    int nResult = -1;

    if( sqlite3_get_table( poDS->GetDB(), osFeatureCountSQL, &papszResult,
                           &nRowCount, &nColCount, &pszErrMsg ) != SQLITE_OK )
    {
        CPLDebug("SQLITE", "Error: %s", pszErrMsg);
        sqlite3_free(pszErrMsg);
        return poLayer->BaseGetFeatureCount(bForce);
    }

    if( nRowCount == 1 && nColCount == 1 )
    {
        nResult = atoi(papszResult[1]);
    }

    sqlite3_free_table( papszResult );

    return nResult;
}
Ejemplo n.º 29
0
bool QgsSpatiaLiteConnection::isRasterlite1Datasource( sqlite3 *handle, const char *table )
{
// testing for RasterLite-1 datasources
  int ret;
  int i;
  char **results = nullptr;
  int rows;
  int columns;
  bool exists = false;
  char table_raster[4192];
  char sql[4192];

  strncpy( table_raster, table, sizeof sql );
  table_raster[ sizeof sql - 1 ] = '\0';

  size_t len = strlen( table_raster );
  if ( strlen( table_raster ) < 9 )
    return false;
  if ( strcmp( table_raster + len - 9, "_metadata" ) != 0 )
    return false;
  // ok, possible candidate
  strcpy( table_raster + len - 9, "_rasters" );

  // checking if the related "_RASTERS table exists
  sprintf( sql, "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '%s'", table_raster );

  ret = sqlite3_get_table( handle, sql, &results, &rows, &columns, nullptr );
  if ( ret != SQLITE_OK )
    return false;
  if ( rows < 1 )
    ;
  else
  {
    for ( i = 1; i <= rows; i++ )
    {
      if ( results[( i * columns ) + 0] )
      {
        const char *name = results[( i * columns ) + 0];
        if ( name )
          exists = true;
      }
    }
  }
  sqlite3_free_table( results );
  return exists;
}
Ejemplo n.º 30
0
BOOL GetCityIDByName(const char *name,char *cityid)
{
	char **azResult;
	int row_num = 0,column_num = 0;
	char sql[1024] = {0};
	if(database_open() == FALSE) return FALSE;
	sprintf(sql,"select F_CityID from citytable where F_NAME='%s'",name);
	sqlite3_get_table(db,sql,  &azResult, &row_num, &column_num, NULL);
	if(row_num>=1){
		strcpy(cityid,azResult[1]);
		sqlite3_free_table(azResult);
		database_close();
		return TRUE;
	}
	database_close();
	return FALSE;
}