Exemplo n.º 1
0
int MysqlResultSet_next(T R) {
	assert(R);
        if (R->stop)
                return false;
        if (R->maxRows && (R->currentRow++ >= R->maxRows)) {
                R->stop = true;
#if MYSQL_VERSION_ID >= 50002
                /* Seems to need a cursor to work */
                mysql_stmt_reset(R->stmt); 
#else
                /* Bhaa! Where's my cancel method? 
                   Pencil neck mysql developers! */
                while (mysql_stmt_fetch(R->stmt) == 0); 
#endif
                return false;
        }
        if (R->needRebind) {
                if ((R->lastError = mysql_stmt_bind_result(R->stmt, R->bind)))
                        THROW(SQLException, "mysql_stmt_bind_result -- %s", mysql_stmt_error(R->stmt));
                R->needRebind = false;
        }
        R->lastError = mysql_stmt_fetch(R->stmt);
        if (R->lastError == 1)
                THROW(SQLException, "mysql_stmt_fetch -- %s", mysql_stmt_error(R->stmt));
        return ((R->lastError == MYSQL_OK) || (R->lastError == MYSQL_DATA_TRUNCATED));
}
Exemplo n.º 2
0
static bool database_fetch(database_handler_t* handler)
{
	if (mysql_stmt_fetch(handler->stmt))
	{
		if (mysql_stmt_errno(handler->stmt) == CR_SERVER_GONE_ERROR)
		{
			debug_log("try to reopen mysql\n");
			if (!database_handler_reopen(handler))
			{
				error_log("reopen failure:%d,%s\n", mysql_stmt_errno(handler->stmt), mysql_stmt_error(handler->stmt));
				return false;
			}
			debug_log("reopen success\n");
			if (mysql_stmt_fetch(handler->stmt))
			{
				/*error_log("mysql_stmt_prepare error:%d,%s\n", mysql_stmt_errno(handler->stmt), mysql_stmt_error(handler->stmt));*/
				return false;
			}
			return true;
		}
		/*error_log("mysql_stmt_fetch error:%s\n", mysql_stmt_error(handler->stmt));*/
		return false;
	}
	return true;
}
Exemplo n.º 3
0
gint
mysql_cursor_fetch (GSQLCursor *cursor, gint rows)
{
	GSQL_TRACE_FUNC;
	
	GSQLEMySQLCursor  *e_cursor = NULL;
	gchar error_str[2048];
	gint ret = 1;
	
	g_return_if_fail (GSQL_CURSOR (cursor) != NULL);
	e_cursor = cursor->spec;
	
	mysql_variable_clear (cursor);
	
	if (ret = mysql_stmt_fetch (e_cursor->statement))
	{
		switch (ret)
		{
			case MYSQL_NO_DATA:
				return 0;
			case MYSQL_DATA_TRUNCATED:
				gsql_message_add (gsql_session_get_workspace (cursor->session), GSQL_MESSAGE_WARNING,
								  N_("Data truncated. It is mean that internal error occured. Please, report this bug."));
				return 0;
			default:
				g_sprintf (error_str, "Error occured: [%d]%s", ret, mysql_stmt_error (e_cursor->statement));
				gsql_message_add (gsql_session_get_workspace (cursor->session), GSQL_MESSAGE_WARNING,
								  error_str);
				return -1;
		}
	} 
	
	return 1;
}
Exemplo n.º 4
0
    Row Cursor::fetch()
    {
      log_debug("mysql_stmt_fetch(" << stmt << ')');
      int ret = mysql_stmt_fetch(stmt);

      if (ret == MYSQL_DATA_TRUNCATED)
      {
        // fetch column data where truncated
        MYSQL_FIELD* fields = mysqlStatement->getFields();
        for (unsigned n = 0; n < row->getSize(); ++n)
        {
          if (*row->getMysqlBind()[n].length > row->getMysqlBind()[n].buffer_length)
          {
            // actual length was longer than buffer_length, so this column is truncated
            fields[n].length = *row->getMysqlBind()[n].length;
            row->initOutBuffer(n, fields[n]);

            log_debug("mysql_stmt_fetch_column(" << stmt << ", BIND, " << n
                << ", 0) with " << fields[n].length << " bytes");
            if (mysql_stmt_fetch_column(stmt, row->getMysqlBind() + n, n, 0) != 0)
              throw MysqlStmtError("mysql_stmt_fetch_column", stmt);
          }
        }
      }
      else if (ret == MYSQL_NO_DATA)
      {
        log_debug("MYSQL_NO_DATA");
        row = 0;
        return Row();
      }
      else if (ret == 1)
        throw MysqlStmtError("mysql_stmt_fetch", stmt);

      return Row(&*row);
    }
Exemplo n.º 5
0
/*==========================================
 * ステートメント結果セットの次レコードを取得
 *------------------------------------------
 */
bool sqldbs_stmt_fetch(struct sqldbs_stmt *st)
{
	int ret = 0;
	const char *msg = NULL;

	nullpo_retr(false, st);

	ret = mysql_stmt_fetch(st->stmt);

	switch(ret) {
		case 0:
			return true;
		case MYSQL_NO_DATA:
			return false;
		case MYSQL_DATA_TRUNCATED:
			msg = "data truncated";
			break;
		default:
			msg = mysql_stmt_error(st->stmt);
			break;
	}
	if(msg) {
		printf("DB server Error - %s\n  %s\n\n", msg, st->query);
	}

	return false;
}
Exemplo n.º 6
0
static int
table_mysql_check(int service, const char *key)
{
	MYSQL_STMT	*stmt;
	int		 r, s;

	stmt = table_mysql_query(key, service);
	if (stmt == NULL)
		return (-1);

	r = -1;
	s = mysql_stmt_fetch(stmt);

	if (s == 0)
		r = 1;
	else if (s == MYSQL_NO_DATA)
		r = 0;
	else
		log_warnx("warn: table-mysql: mysql_stmt_fetch: %s",
		    mysql_stmt_error(stmt));

	if (mysql_stmt_free_result(stmt))
		log_warnx("warn: table-mysql: mysql_stmt_free_result: %s",
		    mysql_stmt_error(stmt));

	return (r);
}
Exemplo n.º 7
0
static int perf1(MYSQL *mysql)
{
  int rc;
  MYSQL_STMT *stmt;
  const char *stmtstr= "SELECT s.emp_no, s.salary, e.emp_no, e.first_name, e.last_name, e.gender FROM salaries s, employees e WHERE s.emp_no = e.emp_no";

  rc= mysql_select_db(mysql, "employees");
  if (rc)
  {
    diag("Employees database not installed");
    return SKIP;
  }

  stmt= mysql_stmt_init(mysql);

  diag("prepare");
  rc= mysql_stmt_prepare(stmt, stmtstr, (unsigned long)strlen(stmtstr));
  check_stmt_rc(rc, stmt);

  diag("execute");
  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);

  diag("store");
  rc= mysql_stmt_store_result(stmt);
  check_stmt_rc(rc, stmt);

  diag("fetch");
  while (!mysql_stmt_fetch(stmt));

  mysql_stmt_close(stmt);
  return OK;
}
Exemplo n.º 8
0
/* bool fetch (); */
NS_IMETHODIMP jxMySQL50Statement::Fetch(PRBool *_retval)
{
	if (mConnection == nsnull)
    {
        SET_ERROR_RETURN (JX_MYSQL50_ERROR_NOT_CONNECTED);
    }

    if (mSTMT == nsnull)
    {
        SET_ERROR_RETURN (JX_MYSQL50_ERROR_STMT_NULL);
    }

	PRInt32	ret = mysql_stmt_fetch(mSTMT);
	*_retval = PR_FALSE;

	if (!ret || ret == MYSQL_DATA_TRUNCATED) {
		*_retval = PR_TRUE;
	} else if (ret == MYSQL_NO_DATA) {
	   	*_retval = PR_FALSE;
	} else 
    {
		// const char* err = mysql_stmt_error(mSTMT);
		PRUint32 eno = mysql_stmt_errno(mSTMT);
		if ( eno == 2050 || eno == 2051 || eno == 2052 || eno == 2053)
        {
		  // No result set
		  return NS_OK;
        }

		SET_ERROR_RETURN (JX_MYSQL50_MYSQL_ERROR);
	}

	return NS_OK;

}
Exemplo n.º 9
0
bool embeddedResult::fetchNext()
{
    if(!d->driver)
        return false;
    if (d->preparedQuery) {
#if MYSQL_VERSION_ID >= 40108
        int nRC = mysql_stmt_fetch(d->stmt);
        if (nRC) {
#ifdef MYSQL_DATA_TRUNCATED
            if (nRC == 1 || nRC == MYSQL_DATA_TRUNCATED)
#else
            if (nRC == 1)
#endif // MYSQL_DATA_TRUNCATED
                setLastError(qMakeStmtError(QCoreApplication::translate("embeddedResult",
                                    "Unable to fetch data"), QSqlError::StatementError, d->stmt));
            return false;
        }
#else
        return false;
#endif
    } else {
        d->row = mysql_fetch_row(d->result);
        if (!d->row)
            return false;
    }
    setAt(at() + 1);
    return true;
}
Exemplo n.º 10
0
IResultRow *MyBoundResults::FetchRow()
{
	if (!MoreRows())
	{
		m_CurRow = m_RowCount + 1;
		return NULL;
	}

	m_CurRow++;

	if (m_bUpdatedBinds)
	{
		if (mysql_stmt_bind_result(m_stmt, m_bind) != 0)
		{
			return NULL;
		}
		m_bUpdatedBinds = false;
	}

	/* We should be able to get another row */
	int err = mysql_stmt_fetch(m_stmt);
	if (err == 0 || err == MYSQL_DATA_TRUNCATED)
	{
		return this;
	}

	if (err == MYSQL_NO_DATA && m_CurRow == m_RowCount)
	{
		return this;
	}

	/* Some sort of error occurred */
	return NULL;
}
Exemplo n.º 11
0
        bool mysql_stmt_resultset::next()
        {
            if (stmt_ == NULL)
                return false;

            if (status_ == -1)
            {
                get_results();

                if (status_ == -1)
                    return false;
            }

            int res = mysql_stmt_fetch(stmt_);

            if (res == 1 || res == MYSQL_DATA_TRUNCATED)
                throw database_exception(last_stmt_error(stmt_));

            if (res == MYSQL_NO_DATA)
            {
                return false;
            }

            return true;

        }
Exemplo n.º 12
0
bool database::get_oauth_user(char *access_token, int *OAuthUserID, int *UserID,
                              int *expires_at) {
  MYSQL_STMT *stmt;
  MYSQL_BIND pbind[1];
  memset(pbind, 0, sizeof(pbind));

  bool result = false;

  pbind[0].buffer_type = MYSQL_TYPE_STRING;
  pbind[0].buffer = (char *)access_token;
  pbind[0].buffer_length = strnlen(access_token, 512);

  const char sql[] =
      "SELECT  t.user_id, c.parent_id, t.expires_at FROM "
      "`supla_oauth_access_tokens` AS t, `supla_oauth_clients` AS c WHERE c.id "
      "= t.client_id AND c.parent_id != 0 AND t.expires_at > "
      "UNIX_TIMESTAMP(NOW()) AND t.scope = 'restapi' AND token = ? LIMIT 1";

  if (stmt_execute((void **)&stmt, sql, pbind, 1, true)) {
    mysql_stmt_store_result(stmt);

    if (mysql_stmt_num_rows(stmt) > 0) {
      MYSQL_BIND rbind[3];
      memset(rbind, 0, sizeof(rbind));

      int _OAuthUserID, _UserID, _expires_at;

      rbind[0].buffer_type = MYSQL_TYPE_LONG;
      rbind[0].buffer = (char *)&_OAuthUserID;

      rbind[1].buffer_type = MYSQL_TYPE_LONG;
      rbind[1].buffer = (char *)&_UserID;

      rbind[2].buffer_type = MYSQL_TYPE_LONG;
      rbind[2].buffer = (char *)&_expires_at;

      if (mysql_stmt_bind_result(stmt, rbind)) {
        supla_log(LOG_ERR, "MySQL - stmt bind error - %s",
                  mysql_stmt_error(stmt));

      } else if (mysql_stmt_fetch(stmt) == 0) {
        if (OAuthUserID != NULL) *OAuthUserID = _OAuthUserID;

        if (UserID != NULL) *UserID = _UserID;

        if (expires_at != NULL) {
          *expires_at = _expires_at;
        }

        result = true;
      }
    }

    mysql_stmt_free_result(stmt);
    mysql_stmt_close(stmt);
  }

  return result;
}
    bool bind_result_t::next_impl()
    {
      if (_handle->debug)
        std::cerr << "MySQL debug: Accessing next row of handle at " << _handle.get() << std::endl;

      auto flag = mysql_stmt_fetch(_handle->mysql_stmt);

      switch (flag)
      {
        case 0:
        case MYSQL_DATA_TRUNCATED:
        {
          bool need_to_rebind = false;
          for (auto& r : _handle->result_param_meta_data)
          {
            if (r.len)
            {
              if (r.bound_is_null)
              {
                *r.text_buffer = nullptr;
                *r.len = 0;
              }
              else
              {
                if (r.bound_len > r.bound_text_buffer.size())
                {
                  if (_handle->debug)
                    std::cerr << "MySQL debug: Need to reallocate buffer at index " << r.index << " for handle at "
                              << _handle.get() << std::endl;
                  need_to_rebind = true;
                  r.bound_text_buffer.resize(r.bound_len);
                  MYSQL_BIND& param = _handle->result_params[r.index];
                  param.buffer = r.bound_text_buffer.data();
                  param.buffer_length = r.bound_text_buffer.size();

                  if (mysql_stmt_fetch_column(_handle->mysql_stmt, _handle->result_params.data() + r.index, r.index, 0))
                    throw sqlpp::exception(std::string("MySQL: Fetch column after reallocate failed: ") +
                                           mysql_stmt_error(_handle->mysql_stmt));
                }
                *r.text_buffer = r.bound_text_buffer.data();
                *r.len = r.bound_len;
              }
            }
            if (r.is_null)
              *r.is_null = r.bound_is_null;
          }
          if (need_to_rebind)
            bind_impl();
        }
          return true;
        case 1:
          throw sqlpp::exception(std::string("MySQL: Could not fetch next result: ") +
                                 mysql_stmt_error(_handle->mysql_stmt));
        case MYSQL_NO_DATA:
          return false;
        default:
          throw sqlpp::exception("MySQL: Unexpected return value for mysql_stmt_fetch()");
      }
    }
Exemplo n.º 14
0
int test_sp_reset1(MYSQL *mysql)
{
  int rc;
  MYSQL_STMT *stmt;
  MYSQL_BIND bind[1];

  char tmp[20];
  char *stmtstr= "CALL P1(?)";

  rc= mysql_query(mysql, "DROP PROCEDURE IF EXISTS p1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "CREATE PROCEDURE p1(OUT p_out VARCHAR(19))" 
                         "BEGIN "
                          "  SET p_out = 'foo';"
                          "  SELECT 'foo' FROM DUAL;"
                          "  SELECT 'bar' FROM DUAL;"
                         "END");
  check_mysql_rc(rc, mysql);

  stmt= mysql_stmt_init(mysql);
  check_mysql_rc(rc, mysql);

  rc= mysql_stmt_prepare(stmt, stmtstr, strlen(stmtstr));
  check_stmt_rc(rc, stmt);

  memset(tmp, 0, sizeof(tmp));
  memset(bind, 0, sizeof(MYSQL_BIND));
  bind[0].buffer= tmp;
  bind[0].buffer_type= MYSQL_TYPE_STRING;
  bind[0].buffer_length= 4;

  mysql_stmt_bind_param(stmt, bind);

  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_store_result(stmt);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_next_result(stmt);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_fetch(stmt);
  check_stmt_rc(rc, stmt);

  /* mysql_stmt_reset should set statement in prepared state.
   * this means: all subsequent result sets should be flushed.
   * Let's try!
   */ 
  rc= mysql_stmt_reset(stmt);
  check_stmt_rc(rc, stmt);

  rc= mysql_query(mysql, "DROP PROCEDURE p1");
  check_mysql_rc(rc, mysql);

  mysql_stmt_close(stmt);
  return OK;
}
Exemplo n.º 15
0
bool selectStmt()
{
    std::unique_ptr<MYSQL, MysqlDestroy> mysql{mysql_init(nullptr)};
    if (mysql_options(&*mysql, MYSQL_SET_CHARSET_NAME, "utf8") != 0) {
        printf("error mysql_options\n");
        return false;
    }
    if (!mysql_real_connect(&*mysql, IP.c_str(), USER.c_str(), PASSWORD.c_str(), "mytest", PORT,nullptr,0)) {
        printf("error mysql_real_connect\n");
        return false;
    }

    const std::string sql = "select fid, fname, fsid from test where fid = 1";
    std::unique_ptr<MYSQL_STMT, MysqlStmtDestroy> mysql_stmt{mysql_stmt_init(&*mysql)};
    mysql_stmt_prepare(&*mysql_stmt, sql.data(), sql.size());

    if (mysql_stmt_execute(&*mysql_stmt) != 0) {
        printf("error mysql_stmt_execute\n");
        return false;
    }
    mysql_stmt_store_result(&*mysql_stmt);

    std::array<MYSQL_BIND,3> bind{};
    std::array<std::array<char, 50>, 3> bind_buffer{};    
    std::array<unsigned long, 3> bind_length{};
    std::memset(bind.data(), 0, sizeof(bind));

    bind[0].buffer = bind_buffer[0].data();
    bind[0].buffer_length = 50;
    bind[0].length = &bind_length[0];

    bind[1].buffer = bind_buffer[1].data();
    bind[1].buffer_length = 50;
    bind[1].length = &bind_length[1];

    bind[2].buffer = bind_buffer[2].data();
    bind[2].buffer_length = 50;
    bind[2].length = &bind_length[2];

    if (mysql_stmt_bind_result(&*mysql_stmt, bind.data())) {
        printf("mysql_stmt_bind_result error\n");
        return false;
    }

    while (mysql_stmt_fetch(&*mysql_stmt) == 0) {
        int fid = 0;
        std::memcpy(&fid, bind[0].buffer, *bind[0].length);

        char* p = (char*)bind[1].buffer;
        for (unsigned long i = 0; i != *bind[1].length; ++i) {
            printf("%c ", p[i]);
        }
        printf("\n");
    }
    return true;
}
Exemplo n.º 16
0
bool PreparedResultSet::_NextRow()
{
    /// Only called in low-level code, namely the constructor
    /// Will iterate over every row of data and buffer it
    if (m_rowPosition >= m_rowCount)
        return false;

    int retval = mysql_stmt_fetch(m_stmt);
    return retval == 0 || retval == MYSQL_DATA_TRUNCATED;
}
Exemplo n.º 17
0
static int dbd_mysql_get_row(apr_pool_t *pool, apr_dbd_results_t *res,
                             apr_dbd_row_t **row, int rownum)
{
    MYSQL_ROW r = NULL;
    int ret = 0;

    if (res->statement) {
        if (res->random) {
            if (rownum > 0) {
                mysql_stmt_data_seek(res->statement, (my_ulonglong) --rownum);
            }
            else {
                return -1; /* invalid row */
            }
        }
        ret = mysql_stmt_fetch(res->statement);
        switch (ret) {
        case 1:
            ret = mysql_stmt_errno(res->statement);
            break;
        case MYSQL_NO_DATA:
            ret = -1;
            break;
        default:
            ret = 0; /* bad luck - get_entry will deal with this */
            break;
        }
    }
    else {
        if (res->random) {
            if (rownum > 0) {
                mysql_data_seek(res->res, (my_ulonglong) --rownum);
            }
            else {
                return -1; /* invalid row */
            }
        }
        r = mysql_fetch_row(res->res);
        if (r == NULL) {
            ret = -1;
        }
    }
    if (ret == 0) {
        if (!*row) {
            *row = apr_palloc(pool, sizeof(apr_dbd_row_t));
        }
        (*row)->row = r;
        (*row)->res = res;
        (*row)->len = mysql_fetch_lengths(res->res);
    }
    else {
        apr_pool_cleanup_run(res->pool, res->res, free_result);
    }
    return ret;
}
Exemplo n.º 18
0
static int test_bug11111(MYSQL *mysql)
{
  MYSQL_STMT    *stmt;
  MYSQL_BIND    my_bind[2];
  char          buf[2][20];
  ulong         len[2];
  int i;
  int rc;
  const char *query= "SELECT DISTINCT f1,ff2 FROM v1";

  rc= mysql_query(mysql, "drop table if exists t1, t2, v1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "drop view if exists t1, t2, v1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "create table t1 (f1 int, f2 int)");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "create table t2 (ff1 int, ff2 int)");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "create view v1 as select * from t1, t2 where f1=ff1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "insert into t1 values (1,1), (2,2), (3,3)");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "insert into t2 values (1,1), (2,2), (3,3)");
  check_mysql_rc(rc, mysql);

  stmt= mysql_stmt_init(mysql);

  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  check_stmt_rc(rc, stmt);
  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);

  memset(my_bind, '\0', sizeof(my_bind));
  for (i=0; i < 2; i++)
  {
    my_bind[i].buffer_type= MYSQL_TYPE_STRING;
    my_bind[i].buffer= (uchar* *)&buf[i];
    my_bind[i].buffer_length= 20;
    my_bind[i].length= &len[i];
  }

  rc= mysql_stmt_bind_result(stmt, my_bind);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_fetch(stmt);
  check_stmt_rc(rc, stmt);
  FAIL_UNLESS(!strcmp(buf[1],"1"), "buf[1] != '1'");
  mysql_stmt_close(stmt);
  rc= mysql_query(mysql, "drop view v1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "drop table t1, t2");
  check_mysql_rc(rc, mysql);

  return OK;
}
Exemplo n.º 19
0
int test_sp_reset(MYSQL *mysql)
{
 int i, rc;
  MYSQL_STMT *stmt;
  int a[] = {10,20,30};
  MYSQL_BIND bind[3];
  char *stmtstr= "CALL P1(?,?,?)";

  rc= mysql_query(mysql, "DROP PROCEDURE IF EXISTS p1");
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "CREATE PROCEDURE p1(OUT p_out VARCHAR(19), IN p_in INT, INOUT p_inout INT)" 
                         "BEGIN "
                          "  SET p_in = 300, p_out := 'This is OUT param', p_inout = 200; "
                          "  SELECT p_inout, p_in, substring(p_out, 9);"
                         "END");
  check_mysql_rc(rc, mysql);

  stmt= mysql_stmt_init(mysql);
  check_mysql_rc(rc, mysql);

  rc= mysql_stmt_prepare(stmt, stmtstr, strlen(stmtstr));
  check_stmt_rc(rc, stmt);

  FAIL_IF(mysql_stmt_param_count(stmt) != 3, "expected param_count=3");

  memset(bind, 0, sizeof(MYSQL_BIND) * 3);
  for (i=0; i < 3; i++)
  {
    bind[i].buffer= &a[i];
    bind[i].buffer_type= MYSQL_TYPE_LONG;
  }
  bind[0].buffer_type= MYSQL_TYPE_NULL;
  rc= mysql_stmt_bind_param(stmt, bind);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_fetch(stmt);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_reset(stmt);
  check_stmt_rc(rc, stmt);

  /*connection shouldn't be blocked now */

  rc= mysql_query(mysql, "DROP PROCEDURE p1");
  check_mysql_rc(rc, mysql);

  rc= mysql_stmt_close(stmt);
  return OK;
}
Exemplo n.º 20
0
 bool next()
 {
     if (!stmt)
         return false;
     int rc = mysql_stmt_fetch(*stmt);
     if (rc == MYSQL_NO_DATA)
         return false;
     else if (rc)
         fail(mysql_stmt_error(*stmt));
     else
         return true;
 }
Exemplo n.º 21
0
static int test_view_star(MYSQL *mysql)
{
  MYSQL_STMT *stmt;
  int rc, i;
  MYSQL_BIND      my_bind[8];
  char            parms[8][100];
  ulong           length[8];
  const char *query= "SELECT * FROM vt1 WHERE a IN (?,?)";

  rc= mysql_query(mysql, "DROP TABLE IF EXISTS t1, vt1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP VIEW IF EXISTS t1, vt1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "CREATE TABLE t1 (a int)");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "CREATE VIEW vt1 AS SELECT a FROM t1");
  check_mysql_rc(rc, mysql);
  memset(my_bind, '\0', sizeof(MYSQL_BIND));
  for (i= 0; i < 2; i++) {
    sprintf((char *)&parms[i], "%d", i);
    my_bind[i].buffer_type = MYSQL_TYPE_VAR_STRING;
    my_bind[i].buffer = (char *)&parms[i];
    my_bind[i].buffer_length = 100;
    my_bind[i].is_null = 0;
    my_bind[i].length = &length[i];
    length[i] = 1;
  }

  stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_bind_param(stmt, my_bind);
  check_stmt_rc(rc, stmt);

  for (i= 0; i < 3; i++)
  {
    rc= mysql_stmt_execute(stmt);
    check_stmt_rc(rc, stmt);
    rc= mysql_stmt_fetch(stmt);
    FAIL_UNLESS(MYSQL_NO_DATA == rc, "Expected 0 rows");
  }

  mysql_stmt_close(stmt);

  rc= mysql_query(mysql, "DROP TABLE t1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP VIEW vt1");
  check_mysql_rc(rc, mysql);

  return OK;
}
Exemplo n.º 22
0
int CMySQLDynamicRecordSet::FetchRow()
{
	if(m_hStmt)
	{
		int Ret=mysql_stmt_fetch(m_hStmt);
		if(Ret)
		{
			if(Ret==MYSQL_DATA_TRUNCATED)
			{
				m_pDBConnection->ProcessErrorMsg(m_hStmt,"出现数据截断");				
				return DBERR_FETCH_RESULT_FAIL;
			}
			else if(Ret==MYSQL_NO_DATA)
			{
				m_IsEOF=true;
				return DBERR_NO_RECORDS;					
			}
			else
			{
				m_pDBConnection->ProcessErrorMsg(m_hStmt,"获取结果集失败");
				return DBERR_FETCH_RESULT_FAIL;
			}
		}
		
		int ColNum=GetColumnCount();
		for(int i=0;i<ColNum;i++)
		{			

			if(*(m_FetchBuffer[i].is_null))
			{
				m_RowBuffer[i].SetNULLValue(m_pColumnInfos[i].Type);
			}
			else
			{
				if(!CMySQLConnection::MySQLBinValueToDBValue(m_FetchBuffer[i].buffer_type,
					m_FetchBuffer[i].buffer,*(m_FetchBuffer[i].length),
					m_pColumnInfos[i].Type,m_pColumnInfos[i].DigitSize,
					m_RowBuffer[i]))
				{
					return DBERR_BINDPARAMFAIL;
				}				
			}
		}
		m_IsBOF=false;
		m_IsEOF=false;
		return DBERR_SUCCEED;
	}	
	else
	{
		return DBERR_NO_RECORDS;
	}
}
Exemplo n.º 23
0
std::vector<int> DBManager::check_jobs() {
	std::vector<int> job_ids;

	char *stmt_str = "SELECT id FROM wkdd_ldp_jobs WHERE status = 'pending' ORDER BY start_time ASC";
	MYSQL_BIND result[1];
	int my_job_id;

	if (mysql_stmt_prepare(m_stmt, stmt_str, strlen(stmt_str)) != 0) {
		print_stmt_error("could not prepare select statement");
		return job_ids;
	}
	
	if (mysql_stmt_field_count(m_stmt) != 1) {
		print_stmt_error("unexpected column count from select");
		return job_ids;
	}
	
	// initialize result column structures
	memset((void *)result, 0, sizeof(result)); // zero the structures
	
	// set up my_id parameter
	result[0].buffer_type = MYSQL_TYPE_LONG;
	result[0].buffer = (void *) &my_job_id;
	result[0].is_unsigned = 0;
	result[0].is_null = 0;
	
	if (mysql_stmt_bind_result(m_stmt, result) != 0) {
		print_stmt_error("could not bind parameters for select");
		return job_ids;
	}
	
	if (mysql_stmt_execute(m_stmt) != 0) {
		print_stmt_error("could not execute select");
		return job_ids;
	}
	
	// fetch result set into client memory; this is optional, but it allows mysql_stmt_num_rows() to be called to determine the number of rows in the result set
	if (mysql_stmt_store_result(m_stmt) != 0) {
		print_stmt_error("could not buffer result set");
		return job_ids;
	}
	
	while (mysql_stmt_fetch(m_stmt) == 0) {  // fetch each row
		// store into vector
		job_ids.push_back(my_job_id);
	}
	
	// deallocate result set
	mysql_stmt_free_result(m_stmt);
	
	return job_ids;
}
Exemplo n.º 24
0
bool StatementExecutor::fetch()
{
	if (_state < STMT_EXECUTED)
		throw StatementException("Statement is not executed yet");

	int res = mysql_stmt_fetch(_pHandle);

	// we have specified zero buffers for BLOBs, so DATA_TRUNCATED is normal in this case
	if ((res != 0) && (res != MYSQL_NO_DATA) && (res != MYSQL_DATA_TRUNCATED)) 
		throw StatementException("mysql_stmt_fetch error", _pHandle, _query);

	return (res == 0) || (res == MYSQL_DATA_TRUNCATED);
}
Exemplo n.º 25
0
void database::get_client_locations(int ClientID,
                                    supla_client_locations *locs) {
  MYSQL_STMT *stmt;

  const char sql[] =
      "SELECT `id`, `caption` FROM `supla_v_client_location`  WHERE "
      "`client_id` = ?";

  MYSQL_BIND pbind[1];
  memset(pbind, 0, sizeof(pbind));

  pbind[0].buffer_type = MYSQL_TYPE_LONG;
  pbind[0].buffer = (char *)&ClientID;

  if (stmt_execute((void **)&stmt, sql, pbind, 1, true)) {
    my_bool is_null[2];

    MYSQL_BIND rbind[2];
    memset(rbind, 0, sizeof(rbind));

    int id;
    unsigned long size;
    char caption[401];  // utf8

    rbind[0].buffer_type = MYSQL_TYPE_LONG;
    rbind[0].buffer = (char *)&id;
    rbind[0].is_null = &is_null[0];

    rbind[1].buffer_type = MYSQL_TYPE_STRING;
    rbind[1].buffer = caption;
    rbind[1].buffer_length = 401;
    rbind[1].length = &size;
    rbind[1].is_null = &is_null[1];

    if (mysql_stmt_bind_result(stmt, rbind)) {
      supla_log(LOG_ERR, "MySQL - stmt bind error - %s",
                mysql_stmt_error(stmt));
    } else {
      mysql_stmt_store_result(stmt);

      if (mysql_stmt_num_rows(stmt) > 0) {
        while (!mysql_stmt_fetch(stmt)) {
          caption[size] = 0;
          locs->add_location(id, caption);
        }
      }
    }

    mysql_stmt_close(stmt);
  }
}
Exemplo n.º 26
0
static bool db_stmt_step_mysql(const struct db_stmt *stmt, struct db_row *row)
{
    struct db_stmt_mysql *stmt_mysql = (struct db_stmt_mysql *)stmt;

    if (stmt_mysql->must_execute_again) {
        stmt_mysql->must_execute_again = false;
        if (mysql_stmt_execute(stmt_mysql->stmt))
            return false;
    }

    if (!stmt_mysql->result_bind) {
        size_t n_rows = 0;
        for (struct db_row *r = row; r->kind != '\0'; r++)
            n_rows++;

        if (!n_rows)
            return false;

        stmt_mysql->result_bind = calloc(n_rows, sizeof(*stmt_mysql->result_bind));
        if (!stmt_mysql->result_bind)
            return false;

        stmt_mysql->param_bind = calloc(n_rows, sizeof(*stmt_mysql->param_bind));
        if (!stmt_mysql->param_bind) {
            free(stmt_mysql->result_bind);
            return false;
        }

        MYSQL_BIND *result = stmt_mysql->result_bind;
        for (size_t r = 0; r < n_rows; r++) {
            if (row[r].kind == 's') {
                result[r].buffer_type = MYSQL_TYPE_STRING;
                result[r].buffer = row[r].u.s;
            } else if (row[r].kind == 'i') {
                result[r].buffer_type = MYSQL_TYPE_LONG;
                result[r].buffer = &row[r].u.i;
            } else {
                return false;
            }

            result[r].is_null = false;
            result[r].buffer_length = row[r].buffer_length;
        }

        if (mysql_stmt_bind_result(stmt_mysql->stmt, result))
            return false;
    }

    return mysql_stmt_fetch(stmt_mysql->stmt) == 0;
}
Exemplo n.º 27
0
int db_read_fetch() {
	_fetch = mysql_stmt_fetch(_mysql_stmt);
	switch(_fetch) {
		case 1:
			mysql_stmt_close(_mysql_stmt);
			finish_with_error(LOG_ERR, "Failed to fetch prepared MySQL statement result");
			return -1;
			break;
		case MYSQL_NO_DATA:
			return 0;
		default:
			return 1;
	}
}
Exemplo n.º 28
0
int my_cmd_next(db_res_t* res)
{
	int ret;
	struct my_cmd* mcmd;

	mcmd = DB_GET_PAYLOAD(res->cmd);
	if (mcmd->next_flag == 2 || mcmd->next_flag == -2) return 1;

	if (mcmd->st == NULL) {
		ERR("mysql: Prepared statement not found\n");
		return -1;
	}

	ret = mysql_stmt_fetch(mcmd->st);
	
	if (ret == MYSQL_NO_DATA) {
		mcmd->next_flag =  mcmd->next_flag<0?-2:2;
		return 1;
	}
	/* MYSQL_DATA_TRUNCATED is only defined in mysql >= 5.0 */
#if defined MYSQL_DATA_TRUNCATED
	if (ret == MYSQL_DATA_TRUNCATED) {
		int i;
		ERR("mysql: mysql_stmt_fetch, data truncated, fields: %d\n", res->cmd->result_count);
		for (i = 0; i < res->cmd->result_count; i++) {
			if (mcmd->st->bind[i].error /*&& mcmd->st->bind[i].buffer_length*/) {
				ERR("mysql: truncation, bind %d, length: %lu, buffer_length: %lu\n", 
					i, *(mcmd->st->bind[i].length), mcmd->st->bind[i].buffer_length);
			}
		}
		ret = 0;
	}
#endif
	if (mcmd->next_flag <= 0) {
		mcmd->next_flag++;
	}
	if (ret != 0) {
		ERR("mysql: Error in mysql_stmt_fetch (ret=%d): %s\n", ret, mysql_stmt_error(mcmd->st));
		return -1;
	}

	if (update_result(res->cmd->result, mcmd->st) < 0) {
		mysql_stmt_free_result(mcmd->st);
		return -1;
	}

	res->cur_rec->fld = res->cmd->result;
	return 0;
}
Exemplo n.º 29
0
bool MmsServer::CheckWhiteList(unsigned int uid, YYLibMysql * mysql)
{
	// mysql process
	if (!mysql || !mysql->_sql)
		return false;

	YYLibMysql::StmtItem item(mysql->_sql);
	// mysql->Execute("DROP TABLE test1");
	// item.Prepare("CREATE TABLE IF NOT EXISTS test1(idx int AUTO_INCREMENT, id int, label varchar(250), v1 TINYINT, v2 SMALLINT, v3 BIGINT, v4 FLOAT, v5 DOUBLE, PRIMARY KEY(idx) );") << Execute();

	// item.Prepare("INSERT INTO test1(id, label, v1, v2, v3, v4, v5) VALUES (?,?,?,?,?,?,?)") << 10 << buf->buf() << (signed char)3 << (short int)5 << (long long)100 << (float)4.5 << (double)55.5 << Execute();
	// item << 20 << buf->buf() << (signed char)10 << (short int)500 << (long long)100000 << (float)4.455 << (double)55.534543 << Execute();

	char sz[40]; sprintf(sz, "%u", uid);
	std::string sql = "SELECT * FROM mms_whitelist WHERE mms_whitelist_uid="; sql += sz;
	item.Prepare(sql.c_str()) << Execute();
	std::auto_ptr<YYLibMysql::StmtRes> res(item.GetRes());
	if (res->BindResult())
	{
		int column_count = mysql_num_fields(res->_res);
		int row = 0;
		while (!mysql_stmt_fetch(res->_stmt))
		{
			long value;
			char * buf;
			row++;
			for (int i = 0; i < column_count; i++)
			{
				switch(res->_bind[i].buffer_type)
				{
				case MYSQL_TYPE_LONG:
					{
						value = *(long*)res->_bind[i].buffer;
					}
					break;
				case MYSQL_TYPE_STRING:
				case MYSQL_TYPE_VARCHAR:
				case MYSQL_TYPE_VAR_STRING:
					{
						buf = (char*)res->_bind[i].buffer;
					}
					break;
				}
			}
		}
	}

	return true;
}
Exemplo n.º 30
0
/**
 * Convert rows from mysql to db API representation
 */
static inline int db_mysql_convert_rows(const db_con_t* _h, db_res_t* _r)
{
	int row;

	if ((!_h) || (!_r)) {
		LM_ERR("invalid parameter\n");
		return -1;
	}

	if (CON_HAS_PS(_h)) {
		RES_ROW_N(_r) = mysql_stmt_num_rows(CON_PS_STMT(_h));
	} else {
		RES_ROW_N(_r) = mysql_num_rows(CON_RESULT(_h));
	}
	if (!RES_ROW_N(_r)) {
		LM_DBG("no rows returned from the query\n");
		RES_ROWS(_r) = 0;
		return 0;
	}

	if (db_allocate_rows( _r, RES_ROW_N(_r))!=0) {
		LM_ERR("no private memory left\n");
		return -2;
	}

	for(row = 0; row < RES_ROW_N(_r); row++) {
		if (CON_HAS_PS(_h)) {
			mysql_stmt_fetch(CON_PS_STMT(_h));
			//if(mysql_stmt_fetch(CON_PS_STMT(_h))!=1)
			//	LM_ERR("STMT ERR=%s\n",mysql_stmt_error(CON_PS_STMT(_h)));
		} else {
			CON_ROW(_h) = mysql_fetch_row(CON_RESULT(_h));
			if (!CON_ROW(_h)) {
				LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
				RES_ROW_N(_r) = row;
				db_free_rows(_r);
				return -3;
			}
		}
		if (db_mysql_convert_row(_h, _r, &(RES_ROWS(_r)[row])) < 0) {
			LM_ERR("error while converting row #%d\n", row);
			RES_ROW_N(_r) = row;
			db_free_rows(_r);
			return -4;
		}
	}
	return 0;
}