int DbLastRowId(DB_HANDLE handle, DB_ID* id)
{

    if (id == NULL) {
        return MsgLog(DBS_INVARG, "NULL id");
    }

    /* TODO returns a sqlite_int64; can this be cast into an unsigned long?
     * do we need to check this for each platform? */
	*id = (DB_ID) sqlite3_last_insert_rowid((sqlite3*) handle);

	/*
	 * In sqlite, there is no error code; a value of 0 is returned if there
	 * is no matching row.  In this case, convert it to an error code.
	 */

	return (*id != 0) ? 0 : DBS_NOSUCHROW;
}
Пример #2
0
int RollbackManager::getNodeId(const std::string &name)
{
	for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
			iter != knownNodes.end(); ++iter) {
		if (iter->name == name) {
			return iter->id;
		}
	}

	SQLOK(sqlite3_bind_text(stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL));
	SQLRES(sqlite3_step(stmt_knownNode_insert), SQLITE_DONE);
	SQLOK(sqlite3_reset(stmt_knownNode_insert));

	int id = sqlite3_last_insert_rowid(db);
	registerNewNode(id, name);

	return id;
}
Пример #3
0
Replacements::Replacements(sqlite3* db, string name, sqlite_int64 ownerId) :
    mDb(db), mName(name), mOwnerId(ownerId)
{
    exAssert(db!=NULL);
    exAssertDesc(ownerId > 0, "ownerId should be greater null");

	sqlite_int64 groupId = 0;

	stringstream strSql;
	strSql  << "SELECT rowid FROM replacementGroups "
		<< "WHERE name = " << cSqlStrOut(mName)
		<< " AND ownerId = " << mOwnerId;
	string sRowId;
	exec(strSql, mDb, onReadFirstField, &sRowId);
	if (sRowId.length() > 0) {
		groupId = cSqlInFormated<sqlite_int64>(sRowId);
	} else {
		strSql.str(""); //clear
		strSql  << "INSERT INTO replacementGroups "
			<< "(name, ownerId) VALUES ("
			<< cSqlStrOut(mName) << ", "
			<< mOwnerId << ")";
		exec(strSql, mDb);

		groupId = sqlite3_last_insert_rowid(mDb);
	}


	vector<string> rowids;
	strSql.str(""); //clear
	strSql << "SELECT rowid FROM replacements "
		"WHERE groupId = " << cSqlOutFormated(groupId) ;

	exec(strSql, db, onAppendFirstColumnToVector, &rowids);
	for (vector<string>::iterator it = rowids.begin();
		it != rowids.end(); it++) {

			stringstream strRowid(*it);
			sqlite_int64 rowid;
			strRowid >> rowid;
			Replacement* newReplacement = new Replacement(db,  rowid);
			mChildren[newReplacement->getRowId()] = newReplacement;
	}
};
Пример #4
0
void PsmFile::insertMatches(const vector<Match>& matches){

    // insert the result into tables msRunSearchResult, BiblioSpecSearchResult
    char zSql[2048];
    double pValue = -1;

    for(int i = 0; i < reportMatches_; i++) {
        Match tmpMatch = matches.at(i);
        const RefSpectrum* tmpRefSpec = tmpMatch.getRefSpec();
        //        const Spectrum* s = tmpMatch.getExpSpec();

       pValue = -1 * log(tmpMatch.getScore(BONF_PVAL));
        if(isinf( pValue ))
            pValue = 1000;

        sprintf(zSql,
                "insert into msRunSearchResult(runSearchID,scanID,charge,"
                "peptide,preResidue, postResidue, validationStatus) "
                "values(%d,%d,%d,'%s','%s','%s','=')",
                blibRunSearchID_,
                0,//                s->getScanID(),
                0,//tmpRefSpec->getCharge(),
                (tmpRefSpec->getSeq()).c_str(),
                (tmpRefSpec->getPrevAA()).c_str(),
                (tmpRefSpec->getNextAA()).c_str());
        SqliteRoutine::SQL_STMT(zSql, db_);
        
        zSql[0]='\0';
        
        int resultID=(int)sqlite3_last_insert_rowid(db_);
        sprintf(zSql, "insert into BiblioSpecSearchResult "
                "values(%d,%d,%d,%d,%f,%f,'%s')",
                resultID,
                tmpRefSpec->getLibSpecID(),
                tmpMatch.getMatchLibID(),
                i+1,
                tmpMatch.getScore(DOTP),
                pValue,
                tmpRefSpec->getMods().c_str());
        SqliteRoutine::SQL_STMT(zSql, db_);
        zSql[0]='\0';
    } // next match

}
Пример #5
0
void Cache::addVCard(const std::string &fn, const std::string &ln, const std::vector< std::string > &emails, const std::string &data, const std::string &updatedAt) {
    if(fn.length() == 0) {
        std::cerr << "Firstname is empty!" << std::endl;
        return;
    }

    if(ln.length() == 0) {
        std::cerr << "Lastname is empty!" << std::endl;
        return;
    }

    if(emails.size() == 0) {
        std::cerr << "Email is empty!" << std::endl;
        return;
    }

    if(data.length() == 0) {
        std::cerr << "Data is empty!" << std::endl;
        return;
    }

    if(db == NULL) {
        std::cerr << "Database not open!" << std::endl;
        return;
    }

    std::string dt = buildDateTimeString(updatedAt);
    std::stringstream ss;

    // happy sql injecting ;)
    ss << "insert into vcards (FirstName, LastName, VCard, UpdatedAt) values (";
    ss << "'" << fn << "','" << ln << "','" << data << "','" << dt << "')";

    bool b = prepSqlite(ss.str());
    if(b) {
        b = stepSqlite("Failed to add new record to cache database");
        if(b) {
            sqlite3_int64 rowid = sqlite3_last_insert_rowid(db);
            addEmails(emails, rowid);
        } else {
            finalizeSqlite(); // finalize on error only
        }
    }
}
Пример #6
0
sqlite_int64
find_album_art(const char * path, const char * image_data, int image_size)
{
	char * album_art = NULL;
	char * sql;
	char ** result;
	int cols, rows;
	sqlite_int64 ret = 0;
	char * mypath;
	const char * dir;
	struct stat st;

	if( stat(path, &st) == 0 && S_ISDIR(st.st_mode) )
	{
		mypath = NULL;
		dir = path;
	}
	else
	{
		mypath = strdup(path);
		dir = dirname(mypath);
	}

	if( (image_size && (album_art = check_embedded_art(path, image_data, image_size))) ||
	    (album_art = check_for_album_file(dir, path)) )
	{
		sql = sqlite3_mprintf("SELECT ID from ALBUM_ART where PATH = '%q'", album_art ? album_art : path);
		if( (sql_get_table(db, sql, &result, &rows, &cols) == SQLITE_OK) && rows )
		{
			ret = strtoll(result[1], NULL, 10);
		}
		else
		{
			if( sql_exec(db, "INSERT into ALBUM_ART (PATH) VALUES ('%q')", album_art) == SQLITE_OK )
				ret = sqlite3_last_insert_rowid(db);
		}
		sqlite3_free_table(result);
		sqlite3_free(sql);
	}
	free(album_art);
	free(mypath);

	return ret;
}
Пример #7
0
static int linphone_chat_message_store_content(LinphoneChatMessage *msg) {
	LinphoneCore *lc = linphone_chat_room_get_core(msg->chat_room);
	int id = -1;
	if (lc->db) {
		LinphoneContent *content = msg->file_transfer_information;
		char *buf = sqlite3_mprintf("INSERT INTO content VALUES(NULL,%Q,%Q,%Q,%Q,%i,%Q);",
						linphone_content_get_type(content),
						linphone_content_get_subtype(content),
						linphone_content_get_name(content),
						linphone_content_get_encoding(content),
						linphone_content_get_size(content),
						NULL
					);
		linphone_sql_request(lc->db, buf);
		sqlite3_free(buf);
		id = (unsigned int) sqlite3_last_insert_rowid (lc->db);
	}
	return id;
}
Пример #8
0
int QgsStyle::addTag( const QString& tagname )
{
  if ( !mCurrentDB )
    return 0;
  sqlite3_stmt *ppStmt;

  char *query = sqlite3_mprintf( "INSERT INTO tag VALUES (NULL, '%q')", tagname.toUtf8().constData() );
  int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr );
  if ( nErr == SQLITE_OK )
    ( void )sqlite3_step( ppStmt );
  sqlite3_finalize( ppStmt );

  QSettings settings;
  settings.setValue( QStringLiteral( "qgis/symbolsListGroupsIndex" ), 0 );

  emit groupsModified();

  return static_cast< int >( sqlite3_last_insert_rowid( mCurrentDB ) );
}
Пример #9
0
u32 DBH_RegisterUser( char* nUsername, char* nPassword )
{
  u32 uid = 0;

  if ( DBH_UserExistsByName( nUsername ) ) return uid;

  char* pQueryString = malloc( 128 );
  memset( pQueryString, 0, 128 );

  sprintf( pQueryString, "INSERT INTO Users (username, password) VALUES ('%s', '%s')", nUsername, nPassword );
  DBH_Query( pQueryString, NULL, NULL, NULL );

  free( pQueryString );

  // assumes a maximum user id of 2^32
  uid = (u32) sqlite3_last_insert_rowid( DBH_dbhnd );

  return uid;
}
Пример #10
0
int64_t library_image_add(int64_t file)
{
  static const char *sql =
    "INSERT INTO images (fileid) VALUES(?)";
  
  sqlite3_stmt *query;
  
  if (!prepare_query(sql, &query)) {
    return -1;
  }
  
  sqlite3_bind_int64(query, 1, file);
  
  if (!execute(query)) {
    return -1;
  }
  
  return sqlite3_last_insert_rowid(db_handle());
}
Пример #11
0
int main(void) {
    
    sqlite3 *db;
    char *err_msg = 0;
    
    int rc = sqlite3_open(":memory:", &db);
    
    if (rc != SQLITE_OK) {
        
        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        
        return 1;
    }
    
    char *sql = "CREATE TABLE Friends(Id INTEGER PRIMARY KEY, Name TEXT);"
    "INSERT INTO Friends(Name) VALUES ('Tom');"
    "INSERT INTO Friends(Name) VALUES ('Rebecca');"
    "INSERT INTO Friends(Name) VALUES ('Jim');"
    "INSERT INTO Friends(Name) VALUES ('Roger');"
    "INSERT INTO Friends(Name) VALUES ('Robert');";
        
    
    rc = sqlite3_exec(db, sql, 0, 0, &err_msg);
    
    if (rc != SQLITE_OK ) {
        
        fprintf(stderr, "Failed to create table\n");
        fprintf(stderr, "SQL error: %s\n", err_msg);
        sqlite3_free(err_msg);
        
    } else {
        
        fprintf(stdout, "Table Friends created successfully\n");
    }
    
    int last_id = sqlite3_last_insert_rowid(db);
    printf("The last Id of the inserted row is %d\n", last_id);

    sqlite3_close(db);
    
    return 0;
}
/**
 * This method is susceptible to injections. Please make sure filename is 'safe'
 */
uint32_t db_wrapper::insert_file(std::string filename) {
    {
	sqlite3_stmt *ppStmt;
	char sql[1024] = "\0";
	sprintf(sql, "select fileId from files where filename like '%s'", filename.c_str());

	if (SQLITE_OK != sqlite3_prepare_v2(db, sql, -1, &ppStmt, 0)) {
	    std::cout << "Well here's an error (3)..." << std::endl;
	    //error handling
	}

	uint32_t fileId = 0;
	if (sqlite3_step(ppStmt) != SQLITE_DONE) {
	    fileId = sqlite3_column_int(ppStmt,0);
	    sqlite3_finalize(ppStmt);
	    return fileId;
	}
	sqlite3_finalize(ppStmt);
    }

    sqlite3_stmt *ppStmt;
    char sql[1024] = "\0";
    sprintf(sql, "insert into files (filename) VALUES ('%s')", filename.c_str());

    if (SQLITE_OK != sqlite3_prepare_v2(db, sql, -1, &ppStmt, 0)) {
	std::cout << "Well here's an error (4)..." << std::endl;
	//error handling
    }

    uint32_t fileId = 0;
    int rc;
    if (SQLITE_DONE != (rc = sqlite3_step(ppStmt))) {
    	// error handling
    	std::cout << "something went wrong. Error code: " << rc << std::endl;
    	std::cout << sqlite3_errmsg(db) << std::endl;
    }
    fileId = sqlite3_last_insert_rowid(db);

    sqlite3_finalize(ppStmt);

    return fileId;
}
Пример #13
0
Sender * DB::addSender(Sender &snd)
{
	int res;
	SQLOK(bind_text(stmt_add_sender, 1, snd.nick.data(), snd.nick.size(),
			NULL), "binding sender nick");
	SQLOK(bind_text(stmt_add_sender, 2, snd.user.data(), snd.user.size(),
			NULL), "binding sender ident");
	SQLOK(bind_text(stmt_add_sender, 3, snd.host.data(), snd.host.size(),
			NULL), "binding sender host");

	SQLRES(step(stmt_add_sender), SQLITE_DONE,
			"running sender insertion statement");
	SQLOK(reset(stmt_add_sender),
			"reseting sender insertion statement");

	snd.id = sqlite3_last_insert_rowid(dbh);

	senders.push_back(snd);
	return &senders[senders.size() - 1];
}
Пример #14
0
static krb5_error_code
create_cache(krb5_context context, krb5_scache *s)
{
    int ret;

    sqlite3_bind_text(s->icache, 1, s->name, -1, NULL);
    do {
	ret = sqlite3_step(s->icache);
    } while (ret == SQLITE_ROW);
    if (ret != SQLITE_DONE) {
	krb5_set_error_message(context, KRB5_CC_IO,
			       N_("Failed to add scache: %d", ""), ret);
	return KRB5_CC_IO;
    }
    sqlite3_reset(s->icache);

    s->cid = sqlite3_last_insert_rowid(s->db);

    return 0;
}
Пример #15
0
uint64_t EventLogger::logEvent(ExecutionState *state, unsigned event,
            uint64_t count) {
    void *host_callstack[32];

    sqlite3_bind_int(event_insert_stmt_, 1, event);
    sqlite3_bind_int64(event_insert_stmt_, 2, count);

    if (!CollectHostBacktraces) {
        sqlite3_bind_null(event_insert_stmt_, 3);
    } else {
        int btrace_size = backtrace(&host_callstack[0], 32);
        sqlite3_bind_blob(event_insert_stmt_, 3, &host_callstack[0],
                btrace_size * sizeof(void*), NULL);
    }

    int result = sqlite3_step(event_insert_stmt_);
    assert(result == SQLITE_DONE);
    sqlite3_reset(event_insert_stmt_);

    return sqlite3_last_insert_rowid(db_);
}
Пример #16
0
int insert_peerProfile(const char *nick_name, const char *group_name, const char *sex, const char *age, const char *introduction, const char *head_image_path, const char *server_id, const char *server_uid, const char *last_ip, const char *tcp_port, const char *udp_port)
{
	char *errmsg=0;//记录返回的错误信息。
	sqlite3 *db=0; //记录返回的数据库句柄

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

	// 下述函数进行数据库添加操作
	char *szBaseSql = "insert into peers_profile(nick_name,group_name,sex,age,introduction,head_image_path,server_id,server_uid,last_ip,last_tcp_port,last_udp_port) values('";
	char *szSql = v6strcat(23, szBaseSql, nick_name, "','", group_name, "','", sex, "','",age, "','",introduction, "','",head_image_path, "','",server_id, "','",server_uid, "','",last_ip, "','",tcp_port, "','",udp_port,"')");
	int rc=sqlite3_exec(db,szSql,0,0,&errmsg);
	release_db_data((void **)&szSql);
	CHECK_RC(rc,errmsg,db);

	// 下述函数获取数据库插入的数据的ID
	int id = (int) sqlite3_last_insert_rowid(db);

	sqlite3_close(db);
	return id;
}
Пример #17
0
int insert_myProfile(const char *name,const char *sex,const char *age,const char *introduction,const char *head_image_path, const char *v4_port, const char *v6_port)
{
	char *errmsg=0;//记录返回的错误信息。
	sqlite3 *db=0; //记录返回的数据库句柄

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

	//下述函数进行数据库添加操作
	char *szBaseSql = "insert into my_profile(nick_name,sex,age,introduction,head_image_path,v4_port,v6_port) values('";
	char *szSql = v6strcat(15, szBaseSql, name, "','", sex, "','", age, "','",introduction,"','",head_image_path,"','",v4_port,"','",v6_port,"')");
	int rc=sqlite3_exec(db,szSql,0,0,&errmsg);
	release_db_data((void **)&szSql);
	CHECK_RC(rc,errmsg,db);

	//下述函数获取数据库插入的数据的ID
	int id = (int) sqlite3_last_insert_rowid(db);

	sqlite3_close(db);
	return id;
}
Пример #18
0
int insert_serverInformation(const char *name, const char *ip, const char *port, const char *description, const char *uid, const char *upassword)
{
	char *errmsg=0;//记录返回的错误信息。
	sqlite3 *db=0; //记录返回的数据库句柄

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

	//下述函数进行数据库添加操作
	char *szBaseSql = "insert into server_information(name,ip,port,description,uid,upassword) values('";
	char *szSql = v6strcat(13, szBaseSql, name, "','", ip, "','", port, "','",description, "','",uid, "','",upassword,"')");
	int rc=sqlite3_exec(db,szSql,0,0,&errmsg);
	release_db_data((void **)&szSql);
	CHECK_RC(rc,errmsg,db);

	//下述函数获取数据库插入的数据的ID
	int id = (int) sqlite3_last_insert_rowid(db);

	sqlite3_close(db);
	return id;
}
// insert and return parameter's id
int database_handler::insert_parameter(const char* parameter_name, int error_id) {
    char* error_message = NULL;
    std::stringstream s_url_id;
    std::string stmt;
    s_url_id << error_id;

    stmt += "INSERT INTO PARAMETERS (PARAMETER_NAME, ERROR_ID) VALUES('";
    stmt += parameter_name;
    stmt += "',";
    stmt += s_url_id.str();
    stmt += ");";

    sqlite3_exec(db, stmt.c_str(), NULL, 0, &error_message);

    if (error_message) {
        std::cout << error_message << std::endl;
        sqlite3_free(error_message);
        return -1;
    }
    return sqlite3_last_insert_rowid(db);
}
sqlite3_int64 createecu(sqlite3 *db, const char *vin, long ecu, const char *ecudesc) {
	sqlite3_int64 foundecu = getecuid(db, vin, ecu);
	if(0 < foundecu) {
		return foundecu;
	}

	char insert_sql[] = "INSERT INTO ecu (vin,ecu,ecudesc) VALUES (?,?,?)";
	int rc;
	sqlite3_stmt *stmt;

	rc = sqlite3_prepare_v2(db, insert_sql, -1, &stmt, NULL);

	if(SQLITE_OK != rc) {
		fprintf(stderr, "Can't prepare statement %s: %s\n", insert_sql, sqlite3_errmsg(db));
		return -1;
	}

	if(NULL != vin) {
		sqlite3_bind_text(stmt, 1, vin, strlen(vin), NULL);
	} else {
		sqlite3_bind_text(stmt, 1, "", 0, NULL);
	}

	sqlite3_bind_int64(stmt, 2, ecu);

	if(NULL != ecudesc) {
		sqlite3_bind_text(stmt, 3, ecudesc, strlen(ecudesc), NULL);
	} else {
		sqlite3_bind_text(stmt, 3, "", 0, NULL);
	}

	rc = sqlite3_step(stmt);
	if(SQLITE_OK != rc && SQLITE_DONE != rc) {
		fprintf(stderr, "Error stepping ecu insert(%i): %s\n", rc, sqlite3_errmsg(db));
	}

	sqlite3_finalize(stmt);

	return sqlite3_last_insert_rowid(db);
}
Пример #21
0
PRIVATE void create_batch(int format_index, int key_prov_index, int min_lenght, int max_lenght, const char* provider_param)
{
	sqlite3_stmt* insert_new_batch;

	free(batch);
	num_attack_in_batch = 1;
	current_attack_index = 0;
	batch = (AttackData*)malloc( sizeof(AttackData) * num_attack_in_batch);
	batch[0].format_index = format_index;
	batch[0].provider_index = key_prov_index;

	// Check that lengths are in range
	batch[0].min_lenght = __min(__max(__min(max_lenght, min_lenght), key_providers[batch[0].provider_index].min_size), formats[batch[0].format_index].max_plaintext_lenght);
	batch[0].max_lenght = __min(max_lenght, formats[batch[0].format_index].max_plaintext_lenght);
	batch[0].num_keys_served = 0;

	// Put Params
	strcpy(batch[0].params, provider_param);
	sprintf(batch_name, "%s / %s", formats[format_index].name, key_providers[key_prov_index].name);
	sprintf(batch_description, "Length %i - %i", batch[0].min_lenght, batch[0].max_lenght);

	key_providers[key_prov_index].get_param_description(provider_param, batch_name+strlen(batch_name), batch[0].min_lenght, batch[0].max_lenght);

	batch[0].resume_arg[0] = 0;

	// Method to split charset into optimized chunks
	introduce_fast_lm(&batch, &num_attack_in_batch);

	// Insert batch data
	if(!is_benchmark)
	{
		sqlite3_prepare_v2(db, "INSERT INTO Batch (Name,Description) VALUES (?,?);", -1, &insert_new_batch, NULL);
		sqlite3_bind_text(insert_new_batch, 1, batch_name, -1, SQLITE_STATIC);
		sqlite3_bind_text(insert_new_batch, 2, batch_description, -1, SQLITE_STATIC);
		sqlite3_step(insert_new_batch);
		batch_db_id = sqlite3_last_insert_rowid(db);
		sqlite3_finalize(insert_new_batch);
	}
}
Пример #22
0
/**
 * Add a new part to the current tarif.
 *
 * @param   hour The starting hour.
 * @param   min The starting minute.
 * @param   days The days it applies.
 * @param   hourprice The price per hour.
 * @return The tarifpart's id.
 */
gint
CCL_tarifpart_new(guint hour, guint min, guint days, guint hourprice, guint incprice)
{
  gchar *cmd = NULL;
  sqlite3_stmt *stmt = NULL;

  g_return_val_if_fail(-1 == CCL_tarifpart_id_get(hour, min, days), -1);
  g_return_val_if_fail(!CCL_tarifpart_conflicts(hour, min, days, NULL), -1);
  g_return_val_if_fail(days <= 127 && days, -1);
  g_return_val_if_fail(1 <= ccl->tarif_id, -1);

  cmd = sqlite3_mprintf("insert into tarifs\n"
			"(tarif, days, stime, hourprice, incprice)\n"
			"values(%d, %u, '%.2u:%.2u', %u, %u);",
			ccl->tarif_id, days, hour, min, hourprice, incprice);
  sqlite3_prepare(ccl->db, cmd, -1, &stmt, NULL);
  sqlite3_free(cmd);
  sqlite3_step(stmt);
  sqlite3_finalize(stmt);

  return sqlite3_last_insert_rowid(ccl->db);
}
Пример #23
0
bool BRCWriter::Insert(std::string symName, int type, sqlite3_int64 *id)
{
    static char *query = "INSERT INTO Names (name, type) VALUES (?,?)";
    int rc = SQLITE_OK;
    static sqlite3_stmt *handle;
    if (!handle)
    {
        rc = sqlite3_prepare_v2(dbPointer, query, strlen(query)+1, &handle, nullptr);
    }
    if (rc == SQLITE_OK)
    {
        int done = false;
        sqlite3_reset(handle);
        sqlite3_bind_text(handle, 1, symName.c_str(), symName.size(), SQLITE_STATIC);
        sqlite3_bind_int(handle, 2, type);
        while (!done)
        {
            switch(rc = sqlite3_step(handle))
            {
                case SQLITE_BUSY:
                    done = true;
                    break;
                case SQLITE_DONE:
                    rc = SQLITE_OK;
                    done = true;
                    break;
                default:
                    done = true;
                    break;
            }
        }                        
    }
    if (rc == SQLITE_OK)
    {
        *id = sqlite3_last_insert_rowid(dbPointer);
    }
    return rc == SQLITE_OK;
}
Пример #24
0
static int _insert_ud(struct meas_db_state *st, unsigned long meas_id, int dtx,
		      int uplink, const struct gsm_meas_rep_unidir *ud)
{
	unsigned long rowid;

	SCK_OK(st->db, sqlite3_bind_int(st->stmt_ins_ud, 1, meas_id));
	SCK_OK(st->db, sqlite3_bind_int(st->stmt_ins_ud, 2,
					rxlev2dbm(ud->full.rx_lev)));
	SCK_OK(st->db, sqlite3_bind_int(st->stmt_ins_ud, 3,
					rxlev2dbm(ud->sub.rx_lev)));
	SCK_OK(st->db, sqlite3_bind_int(st->stmt_ins_ud, 4, ud->full.rx_qual));
	SCK_OK(st->db, sqlite3_bind_int(st->stmt_ins_ud, 5, ud->sub.rx_qual));
	SCK_OK(st->db, sqlite3_bind_int(st->stmt_ins_ud, 6, dtx));
	SCK_OK(st->db, sqlite3_bind_int(st->stmt_ins_ud, 7, uplink));

	SCK_DONE(st->db, sqlite3_step(st->stmt_ins_ud));

	SCK_OK(st->db, sqlite3_reset(st->stmt_ins_ud));

	return sqlite3_last_insert_rowid(st->db);
err_io:
	exit(1);
}
Пример #25
0
int DBBrowserDB::addRecord(const QString& sTableName)
{
    char *errmsg;
    if (!isOpen()) return false;

    // add record is seldom called, for now this is ok
    // but if we ever going to add a lot of records
    // we should cache the parsed tables somewhere
    sqlb::Table table = sqlb::Table::parseSQL(getObjectByName(sTableName).getsql()).first;
    QString sInsertstmt = table.emptyInsertStmt();
    lastErrorMessage = "";
    logSQL(sInsertstmt, kLogMsg_App);
    setRestorePoint();

    if (SQLITE_OK != sqlite3_exec(_db, sInsertstmt.toUtf8(), NULL, NULL, &errmsg))
    {
        lastErrorMessage = QString::fromUtf8(errmsg);
        qWarning() << "addRecord: " << lastErrorMessage;
        return -1;
    } else {
        return sqlite3_last_insert_rowid(_db);
    }
}
int db_insertTeacher(sqlite3 * db, char * name, double rate, int subjects, int years, char * birthdate){
    sqlite3_stmt * stmt =  NULL;

    int last = -1;
    const char * sql = "INSERT INTO Teachers (name, rate, subjects, years, birthdate) VALUES (?, ?, ?, ?, ?);";
    int rc = sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);
    sqlite3_bind_text(stmt, 1, name, strlen(name), SQLITE_TRANSIENT);
    sqlite3_bind_double(stmt, 2, rate);
    sqlite3_bind_int(stmt, 3, subjects);
    sqlite3_bind_int(stmt, 4, years);
    sqlite3_bind_text(stmt, 5, birthdate, strlen(birthdate), SQLITE_TRANSIENT);
    if(SQLITE_OK != rc)
    {
        printf("Not prepared!\n");
    }
    if (SQLITE_DONE != (rc = sqlite3_step(stmt)))
    {
        printf("Not inserted! %i\n", rc);
    }
    last = (int) sqlite3_last_insert_rowid (db);
    sqlite3_finalize(stmt);
    return last;
 }
Пример #27
0
int64_t
PibDb::addCertificate(const IdentityCertificate& certificate)
{
  const Name& certName = certificate.getName();
  const Name& keyName = certificate.getPublicKeyName();

  if (!hasKey(keyName))
    addKey(keyName, certificate.getPublicKeyInfo());

  sqlite3_stmt* statement;
  sqlite3_prepare_v2(m_database,
                     "INSERT INTO certificates \
                      (key_id, certificate_name, certificate_data) \
                      values ((SELECT id FROM keys WHERE key_name=?), ?, ?)",
                     -1, &statement, nullptr);
  sqlite3_bind_block(statement, 1, keyName.wireEncode(), SQLITE_TRANSIENT);
  sqlite3_bind_block(statement, 2, certName.wireEncode(), SQLITE_TRANSIENT);
  sqlite3_bind_block(statement, 3, certificate.wireEncode(), SQLITE_STATIC);
  sqlite3_step(statement);
  sqlite3_finalize(statement);

  return sqlite3_last_insert_rowid(m_database);
}
Пример #28
0
int DocumentDatabase::insert(sqlite3* db, std::string q)
{
	char* errorMessage;
	sqlite3_exec(db, q.c_str(), NULL, NULL, &errorMessage);
	if (errorMessage)
	{
		std::cout << "Error executing the following SQL command" << std::endl;
		std::cout << q << std::endl;
		std::cout << "Error message:" << errorMessage;
		sqlite3_free(errorMessage);
	}
	int ret = (int)sqlite3_last_insert_rowid(db);
	return ret;
	//sqlite3_stmt* stmt;
	//std::stringstream b;
	//b << q;
	//std::string s = b.str();
	//char *str = &s[0];
	//int result;
	//char *query = str;
	//{
	//	int prepCode = sqlite3_prepare(db, query, -1, &stmt, 0);
	//	if (prepCode == SQLITE_OK)
	//	{
	//		int res = sqlite3_step(stmt);
	//		result = res;
	//		sqlite3_finalize(stmt);
	//	}
	//	else
	//	{
	//		std::cout << "Error executing the following SQL command" << std::endl;
	//		std::cout << q << std::endl;
	//		std::cout << "Error Code:" << prepCode;
	//	}
	//}
	
}
Пример #29
0
int update_peerProfile(const char *uid, const char *nick_name, const char *group_name, const char *sex, const char *age, const char *introduction, const char *head_image_path, const char *server_id, const char *server_uid, const char *last_ip, const char *tcp_port, const char *udp_port)
{
	char *errmsg=0;//记录返回的错误信息。
	sqlite3 *db=0; //记录返回的数据库句柄

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

	// 替换introduction字段中'为''
	char* newintro = replacestr(introduction, "'", "''");

	//下述函数进行数据库添加操作
	int id = atoi(uid);
	char *szSql = NULL;
	if(id == 0)
	{
	    char *szBaseSql = "insert into peers_profile(nick_name,group_name,sex,age,introduction,head_image_path,server_id,server_uid,last_ip,last_tcp_port,last_udp_port) values('";
	    szSql = v6strcat(23, szBaseSql, nick_name, "','", group_name, "','", sex, "','",age, "','",newintro, "','",head_image_path, "','",server_id, "','",server_uid, "','",last_ip, "','",tcp_port, "','",udp_port,"')");
	}
	else
	{
		char *szBaseSql = "insert or replace into peers_profile(uid,nick_name,group_name,sex,age,introduction,head_image_path,server_id,server_uid,last_ip,last_tcp_port,last_udp_port) values('";
	    szSql = v6strcat(25, szBaseSql, uid, "','", nick_name, "','", group_name, "','", sex, "','",age, "','",newintro, "','",head_image_path, "','",server_id, "','",server_uid, "','",last_ip, "','",tcp_port, "','",udp_port,"')");
	}
	int rc=sqlite3_exec(db,szSql,0,0,&errmsg);
	release_db_data((void **)&szSql);
	free(newintro);

	CHECK_RC(rc,errmsg,db);

	//下述函数获取数据库插入的数据的ID
	if(id == 0)
	    id = (int) sqlite3_last_insert_rowid(db);

	sqlite3_close(db);
	return id;
}
Пример #30
0
__int64 database::add_order(const ::TradeGateway::Order *pOrder)
{
	if( !this->is_connected() )
		this->connect();

	std::ostringstream sql;
	sql << "INSERT INTO dt_orders VALUES ("
		<< "'" << pOrder->accountId << "',"
		<< "'" << pOrder->inst.securityID << "',"
		<< ""  << pOrder->inst.securityIDSource<< ","
		<< ""  << pOrder->s << ","
		<< ""  << pOrder->posEfct << ","
		<< ""  << pOrder->type<< ","
		<< ""  << pOrder->lmtPrice<< ","
		<< ""  << pOrder->ordQty << ","
		<< "'" << pOrder->ordId<< "',"
		<< ""  << TradeGateway::New << ","
		<< ""  << pOrder->date<< ","
		<< ""  << pOrder->time<< ","
		<< ""  << 0<< ","
		<< ""  << 0<< ","
		<< ""  << pOrder->ordQty<< ","
		<< "\"" << ""<< "\");";
	
	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();
	}
	else
		return sqlite3_last_insert_rowid( pdb );
}