/*************************************************************************//**
Execute any query contained in the input string.

@retval false if no error. True if error

If the query is a select query which returns a value, the results have to be
retirieved by calling getNextRow()
														 
*****************************************************************************/
bool MySqlConnection::query(const std::string queryStr)
{
	// Execute the query
	int res = mysql_real_query(&connection, queryStr.c_str(), queryStr.size());
	if (res)
	{
		errorPrint();
		return true;
	}
	// Check if there are results as expected

	resetQueryResultInfo();
	result = mysql_store_result(& connection);
	if (result)  // there are rows
	{
		// Retrieve information about the results
		hasRows = true;
		num_fields = mysql_num_fields(result);
		fields = mysql_fetch_fields(result);
		// There is an issue here because mysql_store_result was called but mysql_free_results was not
		// However as we are using only insert queries in this program this should be acceptable

	}
	else  // mysql_store_result() returned nothing; should it have?
	{
		if (mysql_field_count(& connection) == 0)
		{
			// query does not return data
			// (it was not a SELECT)
			num_rows = mysql_affected_rows(&connection);
			//assert(num_rows == 1);
		}
		else // mysql_store_result() should have returned data
		{
			errorPrint();
		}
	}

	return false;
}
Example #2
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    uint32 _s = WorldTimer::getMSTime();

    if (mysql_query(mMysql, sql))
    {
        uint32 lErrno = mysql_errno(mMysql);

        sLog.outErrorDb( "SQL: %s", sql);
        sLog.outErrorDb("[%u] %s", lErrno, mysql_error(mMysql));

        if (HandleMySQLError(lErrno)) // If error is handled, just try again
            return _Query(sql, pResult, pFields, pRowCount, pFieldCount);

        return false;
    }
    else
    {
        DEBUG_FILTER_LOG(LOG_FILTER_SQL_TEXT, "[%u ms] SQL: %s", WorldTimer::getMSTimeDiff(_s,WorldTimer::getMSTime()), sql );
    }

    *pResult = mysql_store_result(mMysql);
    *pRowCount = mysql_affected_rows(mMysql);
    *pFieldCount = mysql_field_count(mMysql);

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Example #3
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!m_Mysql)
        return false;

    {
       boost::timer _s;

        if (mysql_query(m_Mysql, sql))
        {
            uint32 lErrno = mysql_errno(m_Mysql);
            _LOG_INFO(LOG_FILTER_SQL, "SQL: %s", sql);
            _LOG_ERROR(LOG_FILTER_SQL, "[%u] %s", lErrno, mysql_error(m_Mysql));

            if (_HandleMySQLErrno(lErrno))      // If it returns true, an error was handled successfully (i.e. reconnection)
                return _Query(sql, pResult, pFields, pRowCount, pFieldCount);    // We try again

            return false;
        }
        else
            _LOG_DEBUG(LOG_FILTER_SQL, "[%u ms] SQL: %s",(uint32)_s.elapsed(), sql);

        *pResult = mysql_store_result(m_Mysql);
        *pRowCount = mysql_affected_rows(m_Mysql);
        *pFieldCount = mysql_field_count(m_Mysql);
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);

    return true;
}
Example #4
0
bool embeddedResult::reset (const QString& query)
{
    if (!driver() || !driver()->isOpen() || driver()->isOpenError() || !d->driver)
        return false;

    d->preparedQuery = false;

    cleanup();

    //qDebug() << "In reset: " + query;

    const QByteArray encQuery(fromUnicode(d->driver->d->tc, query));
    //const QByteArray encQuery = query.toLocal8Bit();

    if (mysql_real_query(d->driver->d->mysql, encQuery.data(), encQuery.length())) {
        setLastError(qMakeError(QCoreApplication::translate("embeddedResult", "Unable to execute query"),
                     QSqlError::StatementError, d->driver->d));
        return false;
    }
    d->result = mysql_store_result(d->driver->d->mysql);
    if (!d->result && mysql_field_count(d->driver->d->mysql) > 0) {
        setLastError(qMakeError(QCoreApplication::translate("embeddedResult", "Unable to store result"),
                    QSqlError::StatementError, d->driver->d));
        return false;
    }
    int numFields = mysql_field_count(d->driver->d->mysql);
    setSelect(numFields != 0);
    d->fields.resize(numFields);
    d->rowsAffected = mysql_affected_rows(d->driver->d->mysql);

    if (isSelect()) {
        for(int i = 0; i < numFields; i++) {
            MYSQL_FIELD* field = mysql_fetch_field_direct(d->result, i);
            d->fields[i].type = qDecodeMYSQLType(field->type, field->flags);
        }
        setAt(QSql::BeforeFirstRow);
    }
    setActive(true);
    return isActive();
}
Example #5
0
int DBConn::execute(const char *sql, DBDataSet *ds /* = NULL */,
                    bool retryQueryOnFail /* = true */) {
  assert(sql && *sql);
  assert(isOpened());

  {
    bool failure;
    if ((failure = mysql_query(m_conn, sql))) {
      if (retryQueryOnFail) {
        for (int count = 0; count < m_maxRetryOpenOnFail; count++) {
          open(m_server, m_connectTimeout, m_readTimeout);
          failure = mysql_query(m_conn, sql);
          if (!failure) break;
        }
      }
      if (failure) {
        int code = mysql_errno(m_conn);
        throw DatabaseException(code, "Failed to execute SQL '%s': %s (%d)",
                                sql, mysql_error(m_conn), code);
      }
    }
  }

  MYSQL_RES *result = mysql_store_result(m_conn);
  if (!result) {
    int code = mysql_errno(m_conn);
    if (code) {
      throw DatabaseException(code, "Failed to execute SQL '%s': %s (%d)", sql,
                              mysql_error(m_conn), code);
    }
  }

  int affected = mysql_affected_rows(m_conn);
  if (ds) {
    ds->addResult(m_conn, result);
  } else {
    mysql_free_result(result);
  }
  return affected;
}
Example #6
0
void
process_statement (MYSQL *conn, char *stmt_str)
{
MYSQL_RES *res_set;

  if (mysql_query (conn, stmt_str) != 0)  /* the statement failed */
  {
    print_error (conn, "Could not execute statement");
    return;
  }

  /* the statement succeeded; determine whether it returned data */
  res_set = mysql_store_result (conn);
  if (res_set)      /* a result set was returned */
  {
    /* process rows and free the result set */
    process_result_set (conn, res_set);
    mysql_free_result (res_set);
  }
  else              /* no result set was returned */
  {
    /*
     * does the lack of a result set mean that the statement didn't
     * return one, or that it should have but an error occurred?
     */
    if (mysql_field_count (conn) == 0)
    {
      /*
       * statement generated no result set (it was not a SELECT,
       * SHOW, DESCRIBE, etc.); just report rows-affected value.
       */
      printf ("Number of rows affected: %lu\n",
              (unsigned long) mysql_affected_rows (conn));
    }
    else  /* an error occurred */
    {
      print_error (conn, "Could not retrieve result set");
    }
  }
}
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!m_Mysql)
        return false;

    {
        uint32 _s = getMSTime();

        if (mysql_query(m_Mysql, sql))
        {
            uint32 lErrno = mysql_errno(m_Mysql);
            sLog->outInfo(LOG_FILTER_SQL, "SQL: %s", sql);
            sLog->outError(LOG_FILTER_SQL, "[%u] %s", lErrno, mysql_error(m_Mysql));

            if (_HandleMySQLErrno(lErrno))      // If it returns true, an error was handled successfully (i.e. reconnection)
                return _Query(sql, pResult, pFields, pRowCount, pFieldCount);    // We try again

            return false;
        }
        else
            sLog->outDebug(LOG_FILTER_SQL, "[%u ms] SQL: %s", getMSTimeDiff(_s, getMSTime()), sql);

        *pResult = mysql_store_result(m_Mysql);
        *pRowCount = mysql_affected_rows(m_Mysql);
        *pFieldCount = mysql_field_count(m_Mysql);
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);

    return true;
}
Example #8
0
static struct sql_result *
driver_mysql_query_s(struct sql_db *_db, const char *query)
{
	struct mysql_db *db = (struct mysql_db *)_db;
	struct mysql_result *result;
	int ret;

	result = i_new(struct mysql_result, 1);
	result->api = driver_mysql_result;

	if (driver_mysql_do_query(db, query) < 0)
		result->api = driver_mysql_error_result;
	else {
		/* query ok */
		result->affected_rows = mysql_affected_rows(db->mysql);
		result->result = mysql_store_result(db->mysql);
#ifdef CLIENT_MULTI_RESULTS
		/* Because we've enabled CLIENT_MULTI_RESULTS, we need to read
		   (ignore) extra results - there should not be any.
		   ret is: -1 = done, >0 = error, 0 = more results. */
		while ((ret = mysql_next_result(db->mysql)) == 0) ;
#else
		ret = -1;
#endif

		if (ret < 0 &&
		    (result->result != NULL || mysql_errno(db->mysql) == 0)) {
			/* ok */
		} else {
			/* failed */
			if (result->result != NULL)
				mysql_free_result(result->result);
			result->api = driver_mysql_error_result;
		}
	}

	result->api.db = _db;
	result->api.refcount = 1;
	return &result->api;
}
Example #9
0
bool DatabaseMysql::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    {
        // guarded block for thread-safe mySQL request
        ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);

        uint32 _s = getMSTime();

        if (mysql_query(mMysql, sql))
        {
            sLog.outErrorDb( "SQL: %s", sql );
            sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
            return false;
        }
        else
        {
            DEBUG_FILTER_LOG(LOG_FILTER_SQL_TEXT, "[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql );
        }

        *pResult = mysql_store_result(mMysql);
        *pRowCount = mysql_affected_rows(mMysql);
        *pFieldCount = mysql_field_count(mMysql);
        // end guarded block
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Example #10
0
bool Writer::WriteIt(struct page_link* pl, char* p, int size) {

	fstream fp;
	fill_filename(*pl);
	string filename("./HTMLFiles/");
	filename += file;

	fp.open(filename.c_str(), ios_base::out);
	if (!fp.is_open()) {
#ifdef DEBUG
		tp.print( "error:writer is trying to write but cannot to open it error: %s\n", strerror(errno) );
#endif
		return false;
	}

	fp.write(p, min(strlen(p), size));
	fp.flush();

    sql = "insert into pages(host,file,port,date,content) values(\"";
    sql += pl->_host_addr;
    sql += "\",\"";
    if(pl->_host_file != NULL)
        sql += pl->_host_file;
    sql += "\",";
    sql += integer2string(pl->_portnumber);
    sql += ",";
    sql += sqldate;
    sql += ",\"";
    sql += filename;
    sql += "\")";
    
    if((mysql_query(conn, sql.c_str()))||(mysql_affected_rows(conn) <= 0))
    {
        printf("%s", mysql_error(conn));
        return false;
    }

    return true;
}
QueryResult * MySQLDatabase::_StoreQueryResult(DatabaseConnection * con)
{
	MySQLQueryResult * res;
	MySQLDatabaseConnection * db = static_cast<MySQLDatabaseConnection*>(con);
	MYSQL_RES * pRes = mysql_store_result( db->MySql );
	uint32 uRows = (uint32)mysql_affected_rows( db->MySql );
	uint32 uFields = (uint32)mysql_field_count( db->MySql );

	if( uRows == 0 || uFields == 0 || pRes == NULL )
	{
		if( pRes != NULL )
			mysql_free_result( pRes );

		return NULL;
	}

	res = new MySQLQueryResult( pRes, uFields, uRows );
	res->NextRow();
	res->GetExtendedFieldInfo();

	return res;
}
Example #12
0
//执行数据定义语言(DDL)类语句
bool CMysqlStore::Exec(const std::string &ddl)
{
	//清除缓冲
	Clear();

	if(0 == mysql_query(m_connptr,ddl.c_str()))
	{
		//得到受影响的行数
		do{
			m_row +=(unsigned long)mysql_affected_rows(m_connptr);
			//m_increaseID =(long)mysql_insert_id(m_connptr);
		}
		while(!mysql_next_result(m_connptr));
	}
	else
	{
		m_err = mysql_error(m_connptr);
		return false;
	}

	return true;
}
Example #13
0
/*
 * Executes an SQL statement directly. This is required for statements
 * which cannot be prepared.
 */
static int execute_direct (lua_State *L) {
    mysql_rec *m;
    const char *sql;
    MYSQL_RES *res;

    m = (mysql_rec *) luaL_checkudata(L, 1, IS_MYSQL_METATABLE);
    if (!m->mysql) {
        lua_pushliteral(L, "connection is closed");
        lua_error(L);
    }
    sql = luaL_checkstring(L, 2);

    /* close open statement */
    if (m->res) {
        mysql_free_result(m->res);
        m->res = NULL;
    }
    if (m->stmt) {
        mysql_stmt_close(m->stmt);
        m->stmt = NULL;
    }

    /* execute */
    if (mysql_real_query(m->mysql, sql, lua_rawlen(L, 2)) != 0) {
        error(L, m);
    }
    if (mysql_field_count(m->mysql) > 0) {
        /* discard result set, if any */
        if  ((res = mysql_store_result(m->mysql)) == NULL) {
            error(L, m);
        }
        mysql_free_result(res);
        return 0;
    } else {
        /* push number of affected rows */
        lua_pushinteger(L, (lua_Integer) mysql_affected_rows(m->mysql));
        return 1;
    }
}
Example #14
0
/**
 * qdb->execute_update(): Executes the update DML
 *
 * @param db        a pointer of qdb_t object
 * @param query     query string
 *
 * @return a number of affected rows
 */
static int execute_update(qdb_t *db, const char *query)
{
    if (db == NULL || db->connected == false) return -1;

#ifdef _Q_ENABLE_MYSQL
    Q_MUTEX_ENTER(db->qmutex);

    int affected = -1;

    // query
    DEBUG("%s", query);
    if (mysql_query(db->mysql, query) == 0) {
        /* get affected rows */
        if ((affected = mysql_affected_rows(db->mysql)) < 0) affected = -1;
    }

    Q_MUTEX_LEAVE(db->qmutex);
    return affected;
#else
    return -1;
#endif
}
Example #15
0
int sql_connecter::exe_update(const string &sql)
{
	int eft_num = -1;
	_res = mysql_store_result(_mysql_conn);
	close_result();

	if( (eft_num = mysql_query(_mysql_conn, sql.c_str())) != 0){
	//	cout<<"update error!\n"<<endl;
		cout<<"<p> database error:"<<mysql_error(_mysql_conn)<<"</p>"<<endl;
		return eft_num;
	}

	_res = mysql_store_result(_mysql_conn);
	eft_num = mysql_affected_rows(_mysql_conn);//get affected rows

	if(_res != NULL){//if null, not query sql
		mysql_free_result(_res);
	}
	//cout<<"update success affected "<<eft_num<<" rows.\n"<<endl;

	return eft_num;
}
Example #16
0
/**
 * 更新磁盘信息
 * 包括 `disk_used`, `recent_use_time`, `disk_status`
 */
void
update_disk(db_disk_info *disk_info) {

	char sql[MAX_BUF_SIZE];
	memset(sql, 0, sizeof(sql));

	//格式化时间
	struct tm * tm_local = localtime(&disk_info->recent_use_time);
	char str_f_t [MAX_BUF_SIZE];
	strftime(str_f_t, sizeof(str_f_t), "%G-%m-%d %H:%M:%S", tm_local);

    sprintf(sql, "UPDATE `disk_info` SET disk_used = %d, recent_use_time = '%s', disk_status = %d WHERE  disk_id = %d",
    		disk_info->disk_used, str_f_t, disk_info->disk_status, disk_info->disk_id);


	int res = mysql_query(g_conn, sql);
	if (!res) {
		printf("Update %lu rows\n", (unsigned long)mysql_affected_rows(g_conn));
	} else {
		print_mysql_error(NULL);
	}
}
Example #17
0
File: tpbx.c Project: unxs0/unxsVZ
void DeletetPBX(void)
{
#ifdef StandardFields
	sprintf(gcQuery,"DELETE FROM tPBX WHERE uPBX=%u AND ( uOwner=%u OR %u>9 )"
					,uPBX,guLoginClient,guPermLevel);
#else
	sprintf(gcQuery,"DELETE FROM tPBX WHERE uPBX=%u AND %u>9 )"
					,uPBX,guPermLevel);
#endif
	macro_mySQLQueryHTMLError;
	if(mysql_affected_rows(&gMysql)>0)
	{
		unxsSPSLog(uPBX,"tPBX","Del");
		tPBX(LANG_NBR_RECDELETED);
	}
	else
	{
		unxsSPSLog(uPBX,"tPBX","DelError");
		tPBX(LANG_NBR_RECNOTDELETED);
	}

}//void DeletetPBX(void)
Example #18
0
map<string, string> CDatabase_Connection::fetch_assoc()
{
	map<string, string> daten;
	daten["error"] = "false";
	try
	{
		if(this->initialised == false)
			throw "No query found!";
        if(mysql_res == NULL)
            throw "Query failed!";
		mysql_field_seek(mysql_res, 0); //!
		if(mysql_affected_rows(&my) == 0)
			throw "Nothing found! Is your request right??";
		if((row = mysql_fetch_row (mysql_res)) != NULL)
		{
			mysql_field_seek (mysql_res, 0);

			for (i = 0; i < mysql_num_fields (mysql_res); i++)
			{
				field = mysql_fetch_field (mysql_res);
				if (row[i] == NULL)
                    daten[field->name] = "";
                else
                    daten[field->name] = row[i];
			}
		}
	}
	catch(char* error)
	{
		cerr << error << endl;
		daten["error"] = "true";
	}
	catch(...)
	{
		daten["error"] = "true";
	}

	return daten;
}
Example #19
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    uint32 _s = WorldTimer::getMSTime();

    if(mysql_query(mMysql, sql))
    {
        sLog.outLog(LOG_DB_ERR, "SQL: %s", sql );
        sLog.outLog(LOG_DB_ERR, "query ERROR: %s", mysql_error(mMysql));
        return false;
    }
    else
    {
        uint32 queryDiff = WorldTimer::getMSTimeDiff(_s, WorldTimer::getMSTime());
        if (m_db.CheckMinLogTime(queryDiff))
            sLog.outLog(LOG_DB_DIFF, "[%u ms] SQL: %s", queryDiff, sql);

        sLog.outDebug("[%u ms] SQL: %s", queryDiff, sql);
    }

    *pResult = mysql_store_result(mMysql);
    *pRowCount = mysql_affected_rows(mMysql);
    *pFieldCount = mysql_field_count(mMysql);

    if (!*pResult)
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Example #20
0
bool CDBSrcMySql::Open(void)
{
	int re;
	re = mysql_query(m_DBHandle, m_strSql.c_str());

	if (re != 0)
	{
		//fprintf(stderr, "Error: %s\n",mysql_error(m_DBHandle));
		//numrows= 0;
		
		int iError = mysql_errno(m_DBHandle);
		if (iError == CR_SERVER_GONE_ERROR) //2006 server has gone away
		{
			//mysql_ping(m_DBHandle);
			//mysql_query(m_DBHandle, "set names 'gb2312';");
			Uninit();
			//Disconnect();
			Init();
			while(! Connect(m_strConnStr)) 
				Disconnect();
			re = mysql_query(m_DBHandle, m_strSql.c_str());
		}
	}

	if (re == 0)
	{
		m_QueryResult = mysql_store_result(m_DBHandle);
		m_nNumRows = (unsigned int)mysql_affected_rows(m_DBHandle);
		m_nNumFields = (unsigned int)mysql_field_count(m_DBHandle);
		m_nCurrField = 0;
		m_nCurrRow = 0;

		m_Row = mysql_fetch_row(m_QueryResult);

		return true;
	}
	return false;
}
Example #21
0
/**
 * 功能:向数据库写入入库时间
 * 参数:id_card - 车主所持卡id
 * 		 start_time - 入库时间
 * 返回值:写入成功返回1,失败返回0,数据库内部出错返回-1
 */
int record_start_time(const char *id_card,const char *start_time)
{
	MYSQL *mysql;
	char query_str[150];
	int affect_rows;
	mysql = open(host,user,password,database);

	sprintf(query_str,"insert into parking_record(id_num,in_time) values ('%s','%s')",id_card,start_time);

	if(mysql_query(mysql,query_str))
	{
		return -1; // errors
	}

	affect_rows = mysql_affected_rows(mysql);
	mysql_close(mysql);
	if(affect_rows > 0)
	{
		return 1; // insert success
	}
	return 0;

}
Example #22
0
VALUE do_mysql_cCommand_execute_non_query(int argc, VALUE *argv, VALUE self) {
  VALUE connection = rb_iv_get(self, "@connection");
  VALUE mysql_connection = rb_iv_get(connection, "@connection");

  if (mysql_connection == Qnil) {
    rb_raise(eConnectionError, "This connection has already been closed.");
  }

  MYSQL *db = DATA_PTR(mysql_connection);
  VALUE query = data_objects_build_query_from_args(self, argc, argv);
  MYSQL_RES *response = do_mysql_cCommand_execute(self, connection, db, query);

  my_ulonglong affected_rows = mysql_affected_rows(db);
  my_ulonglong insert_id = mysql_insert_id(db);

  mysql_free_result(response);

  if (((my_ulonglong)-1) == affected_rows) {
    return Qnil;
  }

  return rb_funcall(cMysqlResult, ID_NEW, 3, self, INT2NUM(affected_rows), insert_id == 0 ? Qnil : INT2NUM(insert_id));
}
Example #23
0
void updateDemographics(systemDemographics SystemDemographics){
// This function will store the System's New Funds

	//Intializing
	char *SQL = (char*)malloc(sizeof(char) * 1024);

	strcpy(SQL, "UPDATE `destinations` SET `Funds`=");
	strcat(SQL, ftoa(SystemDemographics.funds, 2));
	strcat(SQL, ", `Population`=");
	strcat(SQL, ftoa(SystemDemographics.pop, 2));
	strcat(SQL, " WHERE `ID`=");
	strcat(SQL, ftoa(SystemDemographics.systemID, 0));
	strcat(SQL, ";");

	mysql_query(conn, SQL);

	/* Get the number of affected rows */
	affected_rows = mysql_affected_rows(conn);

	if(affected_rows == 0){
		printf("Could not update System's Funds.\n");
	}
}
Example #24
0
void updatePrice(int systemID, int goodID, float Price){
// This function will update the price for a good in the specified system

	//Intializing
	char *SQL = (char*)malloc(sizeof(char) * 1024);

	strcpy(SQL, "UPDATE `markets` SET `currentValue`=");
	strcat(SQL, ftoa(Price, 2));
	strcat(SQL, " WHERE `locationID`=");
	strcat(SQL, ftoa(systemID, 0));
	strcat(SQL," AND `goodID`=");
	strcat(SQL, ftoa(goodID, 0));
	strcat(SQL, ";");

	mysql_query(conn, SQL);

	/* Get the number of affected rows */
	affected_rows = mysql_affected_rows(conn);

	if(affected_rows == 0){
		printf("Could not update System's Price of Good.\n");
	}
}
Example #25
0
int querySQL(char *str){

    //printf("\nquery - %s\n ",str);
    if (mysql_query(conn, str))
    {
        finish_with_error(conn);
    }
    result = mysql_store_result(conn);
    if (result)
    {
        num_rows = mysql_num_rows(result);
        return 1;
    }else{
        if (mysql_field_count(conn) == 0)
        {
            num_rows = mysql_affected_rows(conn);
            return 1;
        }else{
            finish_with_error(conn);
            return 0;
        }
    }
}
Example #26
0
/*
 * Updates inode in database with information from given sam_db_inode.
 *
 * Return: number affected rows on success, -1 on error
 */
int
sam_db_inode_update(sam_db_context_t *con, sam_db_inode_t *inode)
{
	MYSQL_BIND bind[8];
	memset(bind, 0, sizeof (bind));

	SAMDB_BIND(bind[0], inode->size, MYSQL_TYPE_LONGLONG, FALSE);
	SAMDB_BIND_STR(bind[1], inode->csum);
	SAMDB_BIND(bind[2], inode->modify_time, MYSQL_TYPE_LONG, TRUE);
	SAMDB_BIND(bind[3], inode->uid, MYSQL_TYPE_LONG, TRUE);
	SAMDB_BIND(bind[4], inode->gid, MYSQL_TYPE_LONG, TRUE);
	SAMDB_BIND(bind[5], inode->online, MYSQL_TYPE_TINY, TRUE);
	SAMDB_BIND(bind[6], inode->ino, MYSQL_TYPE_LONG, TRUE);
	SAMDB_BIND(bind[7], inode->gen, MYSQL_TYPE_LONG, TRUE);

	if (sam_db_execute_sql(con, bind, NULL, INO_UPDATE) == NULL) {
		Trace(TR_ERR, "Error updating inode %d.%d",
		    inode->ino, inode->gen);
		return (-1);
	}

	return (mysql_affected_rows(con->mysql));
}
Example #27
0
File: sample.c Project: qtkmz/dojo
int exec_query(MYSQL *conn, char *sql)
{
    if (mysql_query(conn, sql) != 0) {
        printf("Error: mysql_query().[%s]\n", mysql_error(conn));
        return 1;
    }

    {
        my_ulonglong num = mysql_affected_rows(conn);

        printf("affected row: %lld\n", num);
    }

    {
        int last_id;

        last_id = mysql_insert_id(conn);

        printf("last id: %d\n", last_id);
    }

    return 0;
}
Example #28
0
void do_delhelp(CHAR_DATA *ch, char *argument)
{
	MYSQL *conn;
	char buf[MSL];
	int id;
	if(!str_cmp(argument,""))
	{
		send_to_char("Syntax: delhelp <id #>\n\r",ch);
		send_to_char("        Deletes the helpfile with the given ID number.\n\r",ch);
		return;
	}
	conn = open_conn();
        if(!conn)
                return send_to_char("Error opening help database.\n\r",ch);
	if(!is_number(argument))
		return send_to_char("Argument must be a number.\n\r",ch);
	id = atoi(argument);
	sprintf(buf,"DELETE FROM helpfiles WHERE id=%d", id);
	mysql_query(conn, buf);
	sprintf(buf,"%i helpfiles deleted.\n\r", (int)mysql_affected_rows(conn));
	send_to_char(buf,ch);
	do_disc(conn);
}
/*Insert information into Host table*/
Status Host_Info_Table_Insert(MYSQL *my_connection, unsigned int HostID, unsigned int SubnetIfIndex,char *HostName, unsigned int HostType,char *HostIpAddr,  char *HostAddrMask)
{

	int res;
	char sqlbuff[SQLBUFFLEN];
	sprintf(sqlbuff,"insert into Host(HostID,SubnetIfIndex,HostName,HostType,HostIpAddr,HostAddrMask) values(%d,%d,'%s',%d,'%s','%s')",HostID,SubnetIfIndex,HostName,HostType,HostIpAddr,HostAddrMask);
	res=mysql_query(my_connection,sqlbuff);
	if(!res)
	{
#ifdef DATABASE_DEBUG_MESSAGE
		printf("[DEBUG] database_netTopoAutoCatch: Insert %lu rows\n",(unsigned long)mysql_affected_rows(my_connection));
#endif
		return DATABASE_OK;
	}
	else
	{
#ifdef DATABASE_DEBUG_MESSAGE
		fprintf(stderr,"[ERROR] database_netTopoAutoCatch: Insert error %d: %s\n",mysql_errno(my_connection),mysql_error(my_connection));
#endif
		return DATABASE_ERROR;
	}
	
}
Example #30
0
int main(int argc, char *argv[])
{
    MYSQL my_conn;
    int res;

    mysql_init(&my_conn);
    if (mysql_real_connect(&my_conn, "localhost", "rick","mysql", "foo", 0, NULL, 0))
    {
        printf("Connection success\n");
        //mysql_close(&my_conn);
        char tmpSql[] = "INSERT INTO children(fname, age) VALUES ('Ann',3)";
        //res = mysql_query(&my_conn, tmpSql.c_str());
        res = mysql_query(&my_conn, tmpSql);

        if (!res)
        {
            printf("Inserted %lu rows\n", (unsigned long)mysql_affected_rows(&my_conn));
        }
        else
        {
            fprintf(stderr, "Insert error %d: %s\n",
                    mysql_errno(&my_conn), mysql_error(&my_conn));
        }

        mysql_close(&my_conn);
    }
    else
    {
        fprintf(stderr, "Connection failed\n");
        if (mysql_errno(&my_conn))
        {
            fprintf(stderr, "Connection error %d: %s\n",
                    mysql_errno(&my_conn), mysql_error(&my_conn));
        }
    }
    return EXIT_SUCCESS;
}