예제 #1
0
파일: cosas.cpp 프로젝트: kbaedal/test
bool actualizar_clientes(MYSQL *my_con, std::vector<Cliente> &lista_clientes)
{
    MYSQL_STMT          *stmt;          // Manejador de la consulta preparada.
    MYSQL_BIND          my_bind[14];    // Estructura para los datos de la consulta.
    data_bind_storage   cmb(db_consts::cliente_nc_txt,      // Reservamos espacio para
                            db_consts::cliente_nc_int,      // almacenar los datos
                            db_consts::cliente_max_txt);    // de un cliente.

    // Ponemos la estructura para los datos a 0.
    std::memset(static_cast<void *>(my_bind), 0, sizeof(my_bind));

    // Reservamos manejador
    if((stmt = mysql_stmt_init(my_con)) == NULL)
    {
        print_mysql_error(my_con, "Imposible inicializar el manejador de la consulta.");
        return false;
    }

    // Preparamos la consulta.
    if(mysql_stmt_prepare(stmt, db_queries::upd_cliente.c_str(), db_queries::upd_cliente.size()) != 0)  {
        print_mysql_stmt_error(stmt, "Imposible preparar consulta UPDATE.");
        return false;
    }

    // Asociamos la estructura my_bind al almacen de datos.
    set_mysql_bind(my_bind, cmb, db_binds::cliente_upd_bind);

    // Asociamos los datos a la consulta.
    if(mysql_stmt_bind_param(stmt, my_bind) != 0) {
        print_mysql_stmt_error(stmt, "Imposible asociar los datos a la consulta.");
        return false;
    }

    int i = 1;
    for(auto &&c : lista_clientes) {
        std::cout << "\rActualizando " << lista_clientes.size() << " clientes... ";
        std::cout << utiles::to_string(i, 6, ' ') << "/" << utiles::to_string(lista_clientes.size(), 6, ' ');

        // Rellenamos el "receptaculo" con los datos del cliente. La estructura
        // my_bind está asociada a esta otra estructura, luego la consulta enviará
        // los datos de esta estructura a traves de la estructura my_bind.
        c.fill_mysql_bind(cmb);

        // Procesamos la consulta con los datos.
        if(mysql_stmt_execute(stmt) != 0) {
            print_mysql_stmt_error(stmt, "Imposible ejecutar consulta preparada.");
            return false;
        }

        ++i;
    }

    std::cout << "\tHecho.\n\n";

    mysql_stmt_close(stmt);

    return true;
}
예제 #2
0
bool MySqlPreparedStatement::prepare()
{
    if(isPrepared())
        return true;

    //remove old binds
    RemoveBinds();

    //create statement object
    m_stmt = mysql_stmt_init(m_pMySQLConn);
    if (!m_stmt)
    {
        sLog.outError("SQL: mysql_stmt_init()() failed ");
        return false;
    }

    //prepare statement
    if (mysql_stmt_prepare(m_stmt, m_szFmt.c_str(), m_szFmt.length()))
    {
        sLog.outError("SQL: mysql_stmt_prepare() failed for '%s'", m_szFmt.c_str());
        sLog.outError("SQL ERROR: %s", mysql_stmt_error(m_stmt));
        return false;
    }

    /* Get the parameter count from the statement */
    m_nParams = mysql_stmt_param_count(m_stmt);

    /* Fetch result set meta information */
    m_pResultMetadata = mysql_stmt_result_metadata(m_stmt);
    //if we do not have result metadata
    if (!m_pResultMetadata && strnicmp(m_szFmt.c_str(), "select", 6) == 0)
    {
        sLog.outError("SQL: no meta information for '%s'", m_szFmt.c_str());
        sLog.outError("SQL ERROR: %s", mysql_stmt_error(m_stmt));
        return false;
    }

    //bind input buffers
    if(m_nParams)
    {
        m_pInputArgs = new MYSQL_BIND[m_nParams];
        memset(m_pInputArgs, 0, sizeof(MYSQL_BIND) * m_nParams);
    }

    //check if we have a statement which returns result sets
    if(m_pResultMetadata)
    {
        //our statement is query
        m_bIsQuery = true;
        /* Get total columns in the query */
        m_nColumns = mysql_num_fields(m_pResultMetadata);

        //bind output buffers
    }

    m_bPrepared = true;
    return true;
}
예제 #3
0
파일: record.c 프로젝트: hushouguo/zebra
bool database_handler_reopen(database_handler_t* handler)
{
	uint32_t timeout;
	char buf[64];
	my_bool truncation;

	if (handler->stmt)
	{
		mysql_stmt_close(handler->stmt);
		mysql_close(&handler->mysql_handler);
	}
	mysql_init(&handler->mysql_handler);
	handler->stmt = mysql_stmt_init(&handler->mysql_handler);
	
	timeout = 10;
	if (mysql_options(&handler->mysql_handler, MYSQL_OPT_CONNECT_TIMEOUT, (const char*)&timeout))
	{
		error_log("mysql_options error:%s\n", mysql_error(&handler->mysql_handler));
		return false;
	}

	timeout = 604800;
	snprintf(buf, sizeof(buf), "set wait_timeout=%d", timeout);
	if (mysql_options(&handler->mysql_handler, MYSQL_INIT_COMMAND, buf))
	{
		error_log("mysql set wait_timeout:%d error:%s\n", timeout, mysql_error(&handler->mysql_handler));
		return false;
	}

	snprintf(buf, sizeof(buf), "set interactive_timeout=%d", timeout);
	if (mysql_options(&handler->mysql_handler, MYSQL_INIT_COMMAND, buf))
	{
		error_log("mysql set interactive_timeout:%d error:%s\n", timeout, mysql_error(&handler->mysql_handler));
		return false;
	}

	snprintf(buf, sizeof(buf), "set names utf8");
	if (mysql_options(&handler->mysql_handler, MYSQL_INIT_COMMAND, buf))
	{
		error_log("mysql set names utf8 error:%s\n", mysql_error(&handler->mysql_handler));
		return false;
	}	

	truncation = true;
	if (mysql_options(&handler->mysql_handler, MYSQL_REPORT_DATA_TRUNCATION, (const char*)&truncation))
	{
		error_log("mysql MYSQL_REPORT_DATA_TRUNCATION error:%s\n", mysql_error(&handler->mysql_handler));
		return false;
	}

	if (!mysql_real_connect(&handler->mysql_handler, handler->config.host, handler->config.user, handler->config.passwd, handler->config.db, handler->config.port, NULL, 0))
	{
		error_log("connecting database:%s,%s,%s,%s,%d error: %s\n", handler->config.host, handler->config.user, handler->config.passwd, handler->config.db, handler->config.port, mysql_error(&handler->mysql_handler));
		return false;
	}

	return true;
}
예제 #4
0
mysql_statement::mysql_statement(mysql_database &db, const sql &s)
  : db_(db)
  , result_size(0)
  , host_size(0)
  , stmt(mysql_stmt_init(db()))
  , host_array(0)
{
  prepare(s);
}
예제 #5
0
void PreparedQueryBase::_prepareQuery( Connection& connection ){
    // Prepare the statement structure.
    m_statement = mysql_stmt_init( connection.getNativeHandlePtr() );
    LW_MYSQL_CHECK_FOR_ERRORS( connection, "Failed to initialize prepared statement" );

    // Then prepare the query itself.
    mysql_stmt_prepare( m_statement, m_query.c_str(), m_query.size() );
    LW_MYSQL_STMT_CHECK_FOR_ERRORS( m_statement, "Failed to prepare query" );
}
예제 #6
0
StatementExecutor::StatementExecutor(MYSQL* mysql)
	: _pSessionHandle(mysql)
	, _affectedRowCount(0)
{
	if (!(_pHandle = mysql_stmt_init(mysql)))
		throw StatementException("mysql_stmt_init error");

	_state = STMT_INITED;
}
예제 #7
0
MySQLStore::MySQLStore(const char* file) :
  connection(NULL),
  onReport(NULL)
{
  const char* queries[] =
  {
    // FIND_ROUTE
    "SELECT Repeater, Gateway, Address FROM Routes"
    "  WHERE Call = ?",
    // VERIFY_ADDRESS
    "SELECT COUNT(Call) FROM Gateways"
    "  WHERE Address = ?",
    // RESET_USER_STATE
    "UPDATE Users SET `Enabled` = 0",
    // STORE_USER_SERVER
    "UPDATE Users SET `Server` = ?"
    "  WHERE (`Nick` = ?)",
    // STORE_USER
    "REPLACE INTO Users (`Nick`, `Name`, `Address`)"
    "  VALUES (?, ?, ?)",
    // REMOVE_USER
    "UPDATE Users"
    "  SET `Enabled` = 0 WHERE `Nick` = ?",
    // FIND_ACTIVE_BOT
    "    SELECT `Nick`, `Date`, 1 AS `Priority` FROM Users"
    "      WHERE (`Server` = ?) AND (`Nick` LIKE 's-%') AND (`Enabled` = 1)"
    "  UNION"
    "    SELECT `Nick`, `Date`, 2 AS `Priority` FROM Users"
    "      WHERE (`Nick` LIKE 's-%') AND (`Enabled` = 1)"
    "  ORDER BY `Priority` ASC, `Date` DESC"
    "  LIMIT 1",
    // GET_LAST_MODIFIED_DATE
    "SELECT MAX(`Date`) FROM Tables"
    "  WHERE `Table` = ?",
    // GET_COUNT_BY_DATE
    "SELECT COUNT(*) FROM Tables"
    "  WHERE (`Table` = ?) AND (`Date` = ?)",
    // STORE_TABLE_DATA
    "REPLACE INTO Tables (`Table`, `Date`, `Call1`, `Call2`)"
    "  VALUES (?, ?, ?, ?)"
  };

  connection = mysql_init(NULL);

  mysql_options(connection, MYSQL_READ_DEFAULT_FILE, realpath(file, NULL));
  mysql_real_connect(connection, NULL, NULL, NULL, NULL, 0, NULL, CLIENT_REMEMBER_OPTIONS);

  my_bool active = true;
  mysql_options(connection, MYSQL_OPT_RECONNECT, &active);

  for (size_t index = 0; index < PREPARED_STATEMENT_COUNT; index ++)
  {
    const char* query = queries[index];
    statements[index] = mysql_stmt_init(connection);
    mysql_stmt_prepare(statements[index], query, strlen(query));
  }
}
void
mas_mysqlpfs_mstmt_init( mysqlpfs_t * pfs, mysqlpfs_mstmt_t * mstmt, int nparams, int nresults )
{
  mstmt->stmt = mysql_stmt_init( &pfs->mysql );
  mstmt->pfs = pfs;
/* fprintf( stderr, "nparams: %d; nresults: %d\n", nparams, nresults ); */
  mas_mysqlpfs_mstmt_init_bind( &mstmt->binds.param, nparams );
  mas_mysqlpfs_mstmt_init_bind( &mstmt->binds.result, nresults );
}
예제 #9
0
int mysql_drv_prepare(db_stmt_t *stmt, const char *query)
{
#ifdef HAVE_PS
  MYSQL      *con = (MYSQL *)stmt->connection->ptr;
  MYSQL_STMT *mystmt;
  unsigned int rc;

  if (con == NULL)
    return 1;

  if (use_ps)
  {
    mystmt = mysql_stmt_init(con);
    DEBUG("mysql_stmt_init(%p) = %p", con, mystmt);
    if (mystmt == NULL)
    {
      log_text(LOG_FATAL, "mysql_stmt_init() failed");
      return 1;
    }
    stmt->ptr = (void *)mystmt;
    DEBUG("mysql_stmt_prepare(%p, \"%s\", %d) = %p", mystmt, query, strlen(query), stmt->ptr);
    if (mysql_stmt_prepare(mystmt, query, strlen(query)))
    {
      /* Check if this statement in not supported */
      rc = mysql_errno(con);
      DEBUG("mysql_errno(%p) = %u", con, rc);
      if (rc == ER_UNSUPPORTED_PS)
      {
        log_text(LOG_DEBUG,
                 "Failed to prepare query \"%s\", using emulation",
                 query);
        goto emulate;
      }
      else
      {
        log_text(LOG_FATAL, "mysql_stmt_prepare() failed");
        log_text(LOG_FATAL, "MySQL error: %d \"%s\"", rc,
                 mysql_error(con));
        DEBUG("mysql_stmt_close(%p)", mystmt);
        mysql_stmt_close(mystmt);
        return 1;
      }
    }

    return 0;
  }

 emulate:
#endif /* HAVE_PS */

  /* Use client-side PS */
  stmt->emulated = 1;
  stmt->query = strdup(query);

  return 0;
}
예제 #10
0
bool CACHE_SESSION::save()
{
  bool ret = false;
  MYSQL_STMT   *stmt;
  MYSQL_BIND   bind[2];
  char *query = (char *)("UPDATE cache SET session=? WHERE session_id=?");
  char *binbuff;
  unsigned long binlen;
  int session_id = this->session_id;
  MYSQL *mysql = (MYSQL *)epublisher->get_native_conn();

//zend_printf("LINE %i <br/>\n", __LINE__);
	if( (stmt = mysql_stmt_init(mysql)) )
	{
//zend_printf("LINE %i <br/>\n", __LINE__);
		if( (mysql_stmt_prepare(stmt, query, strlen(query))) == 0 )
		{
//zend_printf("LINE %i <br/>\n", __LINE__);
			binlen = this->get_binsize();		// obtient la taille maximum n�cessaire
			if(binbuff = (char *)EMALLOC(binlen))
			{
//zend_printf("LINE %i <br/>\n", __LINE__);
				binlen = this->serialize_bin((long *)binbuff);		// s�rialise et obtient la taille r�elle

//zend_printf("LINE %i binlen=%li <br/>\n", __LINE__, binlen);
				bind[0].buffer_type = MYSQL_TYPE_VAR_STRING;
				bind[0].buffer = binbuff;
				bind[0].buffer_length = binlen;
				bind[0].is_null= 0;
				bind[0].length= &binlen;

				bind[1].buffer_type= MYSQL_TYPE_LONG;
				bind[1].buffer= (char *)&session_id;
				bind[1].is_null= 0;
				bind[1].length= 0;

				if (mysql_stmt_bind_param(stmt, bind) == 0)
				{
//zend_printf("LINE %i <br/>\n", __LINE__);
					if (mysql_stmt_execute(stmt) == 0)
					{
//zend_printf("LINE %i <br/>\n", __LINE__);
						if(mysql_stmt_affected_rows(stmt) == 1)
						{
//zend_printf("LINE %i <br/>\n", __LINE__);
							ret = true;
						}
					}
				}
				EFREE(binbuff);
			}
		}
		mysql_stmt_close(stmt);
	}
	return(ret);
}
예제 #11
0
파일: test.cpp 프로젝트: longshadian/estl
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;
}
예제 #12
0
VALUE rb_mysql_stmt_new(VALUE rb_client, VALUE sql) {
  mysql_stmt_wrapper *stmt_wrapper;
  VALUE rb_stmt;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *conn_enc;
#endif

  Check_Type(sql, T_STRING);

  rb_stmt = Data_Make_Struct(cMysql2Statement, mysql_stmt_wrapper, rb_mysql_stmt_mark, rb_mysql_stmt_free, stmt_wrapper);
  {
    stmt_wrapper->client = rb_client;
    stmt_wrapper->refcount = 1;
    stmt_wrapper->closed = 0;
    stmt_wrapper->stmt = NULL;
  }

  // instantiate stmt
  {
    GET_CLIENT(rb_client);
    stmt_wrapper->stmt = mysql_stmt_init(wrapper->client);
#ifdef HAVE_RUBY_ENCODING_H
    conn_enc = rb_to_encoding(wrapper->encoding);
#endif
  }
  if (stmt_wrapper->stmt == NULL) {
    rb_raise(cMysql2Error, "Unable to initialize prepared statement: out of memory");
  }

  // set STMT_ATTR_UPDATE_MAX_LENGTH attr
  {
    my_bool truth = 1;
    if (mysql_stmt_attr_set(stmt_wrapper->stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &truth)) {
      rb_raise(cMysql2Error, "Unable to initialize prepared statement: set STMT_ATTR_UPDATE_MAX_LENGTH");
    }
  }

  // call mysql_stmt_prepare w/o gvl
  {
    struct nogvl_prepare_statement_args args;
    args.stmt = stmt_wrapper->stmt;
    args.sql = sql;
#ifdef HAVE_RUBY_ENCODING_H
    // ensure the string is in the encoding the connection is expecting
    args.sql = rb_str_export_to_enc(args.sql, conn_enc);
#endif
    args.sql_ptr = RSTRING_PTR(sql);
    args.sql_len = RSTRING_LEN(sql);

    if ((VALUE)rb_thread_call_without_gvl(nogvl_prepare_statement, &args, RUBY_UBF_IO, 0) == Qfalse) {
      rb_raise_mysql2_stmt_error(stmt_wrapper);
    }
  }

  return rb_stmt;
}
예제 #13
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;
}
예제 #14
0
파일: test.cpp 프로젝트: longshadian/estl
bool insertStmt_mysql_stmt_send_long_data()
{
    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(), "test", PORT, nullptr, 0)) {
        printf("error mysql_real_connect\n");
        return false;
    }

    std::unique_ptr<MYSQL_STMT, MysqlStmtDestroy> mysql_stmt{mysql_stmt_init(&*mysql)};
    std::string sql = "INSERT INTO `txx` (`fblob`, `fname`) VALUES (?, ?)";
    mysql_stmt_prepare(&*mysql_stmt, sql.data(), sql.size());

    std::string fname = "sdfa'a'b'看看空间x";
    std::vector<int32_t> fblob = { 100,0,200,0,123456789,1234567890 };

    std::array<MYSQL_BIND, 2> b{};
    auto fblob_len = fblob.size() * sizeof(int32_t);
    (void)fblob_len;

    //unsigned long len;
    b[0].buffer_type = MYSQL_TYPE_BLOB;
    //b[0].length = &len;

    b[1].buffer_type = MYSQL_TYPE_STRING;
    b[1].buffer = (void*)fname.data();
    unsigned long fname_len = fname.size();
    b[1].length = &fname_len;


    mysql_stmt_bind_param(&*mysql_stmt, b.data());

    /*
    if (mysql_stmt_send_long_data(&*mysql_stmt, 0, (const char*)fblob.data(), fblob_len)) {
        printf("error mysql_stmt_send_long_data\n");
        return false;
    }
    */
    for (const auto& val : fblob) {
        if (mysql_stmt_send_long_data(&*mysql_stmt, 0, (const char*)&val, sizeof(int32_t))) {
            printf("error mysql_stmt_send_long_data 0\n");
            return false;
        }
    }

    if (mysql_stmt_execute(&*mysql_stmt) != 0) {
        printf("error mysql_stmt_execute\n");
        return false;
    }
    return true;
}
예제 #15
0
StatementExecutor::StatementExecutor(MYSQL* mysql)
{
    h = mysql_stmt_init(mysql);

    if (!h)
    {
        throw StatementException("mysql_stmt_init error");
    }

    _state = STMT_INITED;
}
예제 #16
0
static bool my_sharelog(struct server_auxchain *aux,
			const char *rem_host, const char *username,
			const char *our_result, const char *upstream_result,
			const char *reason, const char *solution)
{
	MYSQL *db = srv.db_cxn;
	MYSQL_STMT *stmt;
	MYSQL_BIND bind_param[6];
	unsigned long bind_lengths[6];
	bool rc = false;
	const char *step = "init";
	const char *stmt_sharelog = aux ? aux->db_stmt_auxsharelog : srv.db_stmt_sharelog;

	if(!stmt_sharelog) {
	  	applog(LOG_ERR, "mysql sharelog failed due to missing statement");
		return false;
	}

	stmt = mysql_stmt_init(db);
	if (!stmt)
		return false;

	memset(bind_param, 0, sizeof(bind_param));
	memset(bind_lengths, 0, sizeof(bind_lengths));
	bind_instr(bind_param, bind_lengths, 0, rem_host);
	bind_instr(bind_param, bind_lengths, 1, username);
	bind_instr(bind_param, bind_lengths, 2, our_result);
	bind_instr(bind_param, bind_lengths, 3, upstream_result);
	bind_instr(bind_param, bind_lengths, 4, reason);
	bind_instr(bind_param, bind_lengths, 5, solution);

	step = "prep";
	if (mysql_stmt_prepare(stmt, stmt_sharelog,
			       strlen(stmt_sharelog)))
		goto err_out;

	step = "bind-param";
	if (mysql_stmt_bind_param(stmt, bind_param))
		goto err_out;

	step = "execute";
	if (mysql_stmt_execute(stmt))
		goto err_out;

	rc = true;

out:
	mysql_stmt_close(stmt);
	return rc;

err_out:
	applog(LOG_ERR, "mysql sharelog failed at %s", step);
	goto out;
}
예제 #17
0
void FormAccounts_ButtonAccountAddClicked(GtkButton* button, FormAccounts* fa)
{
	MYSQL_STMT* stmt = NULL;
	MYSQL_BIND param_insert[1];
	gchar* Text = NULL;
	unsigned long TextStrLength;
	const char* mysql_stmt_str = "INSERT INTO accounts(name) VALUES (?);";
	
	
	gtk_input_dialog("Создать новый счёт", "Введите наименование нового счёта.", "", &Text);
	
	if (Text)
	{
		g_print("%s(): создать счёт '%s'\n", __func__, Text);
		
		stmt = mysql_stmt_init(fa->MySQL);
		if (stmt == NULL)
		{
			g_print("%s(): mysql_stmt_init() error.\n", __func__);
			goto END;
		}
		if (mysql_stmt_prepare(stmt, mysql_stmt_str, strlen(mysql_stmt_str)))
		{
			g_print("%s(): mysql_stmt_prepare() error.\n", __func__);
			goto END;
		}
		
		TextStrLength = strlen(Text);
		memset(param_insert, 0, sizeof(param_insert));
		
		param_insert[0].buffer_type   = MYSQL_TYPE_VAR_STRING;
		param_insert[0].buffer        = (void*) Text;
		param_insert[0].buffer_length = TextStrLength + 1;
		param_insert[0].length        = &TextStrLength;
		
		if (mysql_stmt_bind_param(stmt, param_insert))
		{
			g_print("%s(): mysql_stmt_bind() error.\n", __func__);
			goto END;
		}
		
		if (mysql_stmt_execute(stmt))
		{
			g_print("%s(): mysql_stmt_bind() error.\n", __func__);
			goto END;
		}
		
		FormAccounts_UpdateData(fa);
	}
	
END:
	if (Text)    g_free(Text);
	if (stmt)    mysql_stmt_close(stmt);
}
예제 #18
0
int TreeViewCategories_CategoryRenameAddToDatabase(TreeViewCategories* c, gchar* row_cat_name, unsigned int row_id)
{
	MYSQL_STMT* stmt = NULL;
	MYSQL_BIND param_update[2];
	char* stmt_update_str = "UPDATE categories SET name = ? WHERE id = ?;\n";
	unsigned int ret = 1;
	unsigned long row_cat_name_strlen;
	
	
	stmt = mysql_stmt_init(c->MySQL);
	if (stmt == NULL)
	{
		fprintf(stderr, "%s(): mysql_stmt_init() error.\n", __func__);
		ret = 0;
		goto END;
	}
	if (mysql_stmt_prepare(stmt, stmt_update_str, strlen(stmt_update_str)))
	{
		fprintf(stderr, "%s(): mysql_stmt_prepare() error.\n", __func__);
		ret = 0;
		goto END;
	}
	
	memset(param_update, 0, sizeof(param_update));
	
	row_cat_name_strlen = strlen(row_cat_name);
	param_update[0].buffer_type     = MYSQL_TYPE_VAR_STRING;
	param_update[0].buffer          = (void*) row_cat_name;
	param_update[0].buffer_length   = row_cat_name_strlen + 1;
	param_update[0].length          = &row_cat_name_strlen;
	
	param_update[1].buffer_type     = MYSQL_TYPE_LONG;
	param_update[1].buffer          = (void*) &row_id;
	param_update[1].is_unsigned     = 1;
	
	if (mysql_stmt_bind_param(stmt, param_update))
	{
		fprintf(stderr, "%s(): mysql_stmt_bind_param() error.\n", __func__);
		ret = 0;
		goto END;
	}
	
	if (mysql_stmt_execute(stmt))
	{
		fprintf(stderr, "%s(): mysql_stmt_execute() error.\n", __func__);
		ret = 0;
		goto END;
	}
	
END:
	if (stmt != NULL)
		mysql_stmt_close(stmt);
	return ret;
}
예제 #19
0
static MYSQL_STMT *STDCALL
mysql_simple_prepare(MYSQL *mysql_arg, const char *query)
{
 MYSQL_STMT *stmt= mysql_stmt_init(mysql_arg);
 if (stmt && mysql_stmt_prepare(stmt, query, (ulong)strlen(query)))
 {
   mysql_stmt_close(stmt);
   return 0;
 }
 return stmt;
}
예제 #20
0
int MySQLService::ExcuteBinary(const char *cmd, SQLParam *param)
{
    MYSQL_BIND *bind = 0;
    int err = 0;
    MYSQL_STMT *stmt;

    do
    {
        stmt = mysql_stmt_init(_connection);
        if(!stmt)
            break;
        if(mysql_stmt_prepare(stmt, cmd, strlen(cmd)))
        {
            err = mysql_errno(_connection);
            break;
        }

        uint32 count = mysql_stmt_param_count(stmt);

        bind = new MYSQL_BIND[count];
        memset(bind, 0, sizeof(bind) * count);

        for(uint32 i = 0; i < count; i++)
        {
            bind[i].buffer = param[i].data; 
            bind[i].buffer_type = MYSQL_TYPE_BLOB;
            bind[i].length= 0;
            bind[i].buffer_length = param[i].length;
            bind[i].is_null= 0;
            if (mysql_stmt_bind_param(stmt, bind))
            {
                err = mysql_errno(_connection);
                break;
            }
        }

        if(!err)
        {
            if(mysql_stmt_execute(stmt))
            {
                err = mysql_errno(_connection);
            }
        }

    }while(0);
    
    if(stmt)
        mysql_stmt_close(stmt);

    delete [] bind;

    return err;
}
예제 #21
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;
}
예제 #22
0
/**
 * prepare_stmt - Initialize and prepare a query statement.
 * @handle:	connected handle
 * @query:	query statement string to execute
 * @bind_parm:  values for unbound variables (parameters) in @query
 * @nparams:	length of @bind_parms
 * @bind_col:	typed array to contain the column results
 *		==> non-NULL 'is_null'/'error' fields are taken to mean
 *		    that NULL values/errors are not acceptable
 * @ncols:	number of expected columns (length of @bind_col)
 * Return prepared statement handle on success, NULL on error.
 */
MYSQL_STMT *prepare_stmt(MYSQL *handle, const char *query,
			 MYSQL_BIND bind_parm[], unsigned long nparams,
			 MYSQL_BIND bind_col[], unsigned long ncols)
{
	MYSQL_STMT	*stmt;
	unsigned long	param_count;

	if (query == NULL || *query == '\0')
		return NULL;

	/* Initialize statement (fails only if out of memory). */
	stmt = mysql_stmt_init(handle);
	if (stmt == NULL) {
		error("can not allocate handle for \"%s\"", query);
		return NULL;
	}

	if (mysql_stmt_prepare(stmt, query, strlen(query))) {
		error("can not prepare statement \"%s\": %s",
		      query, mysql_stmt_error(stmt));
		goto prepare_failed;
	}

	/* Verify the parameter count */
	param_count = mysql_stmt_param_count(stmt);
	if (nparams != nparams) {
		error("expected %lu parameters for \"%s\" but got %lu",
		      nparams, query, param_count);
		goto prepare_failed;
	}

	if (!validate_stmt_column_count(stmt, query, ncols))
		goto prepare_failed;

	if (nparams && mysql_stmt_bind_param(stmt, bind_parm)) {
		error("can not bind parameter buffers for \"%s\": %s",
		      query, mysql_stmt_error(stmt));
		goto prepare_failed;
	}

	if (mysql_stmt_bind_result(stmt, bind_col)) {
		error("can not bind output buffers for \"%s\": %s",
		      query, mysql_stmt_error(stmt));
		goto prepare_failed;
	}

	return stmt;

prepare_failed:
	(void)mysql_stmt_close(stmt);
	return NULL;
}
예제 #23
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;
}
예제 #24
0
bool CACHE_SESSION::save()
{
  bool ret = false;
  MYSQL_STMT   *stmt;
  MYSQL_BIND   bind[2];
  char *query = (char *)("UPDATE cache SET session=? WHERE session_id=?");
  char *binbuff;
  unsigned long binlen;
  int session_id = this->session_id;
  MYSQL *mysql = (MYSQL *)epublisher->get_native_conn();

	if( (stmt = mysql_stmt_init(mysql)) )
	{
		if( (mysql_stmt_prepare(stmt, query, strlen(query))) == 0 )
		{
			binlen = this->get_binsize();		// get size needed
			if(binbuff = (char *)EMALLOC(binlen))
			{
				memset(binbuff, 0, binlen);
				binlen = this->serialize_bin((long *)binbuff);		// serialize and get the real size

				memset(bind, 0, sizeof(bind));
				
				bind[0].buffer_type = MYSQL_TYPE_VAR_STRING;
				bind[0].buffer = binbuff;
				bind[0].buffer_length = binlen;
				bind[0].is_null= 0;
				bind[0].length= &binlen;

				bind[1].buffer_type= MYSQL_TYPE_LONG;
				bind[1].buffer= (char *)&session_id;
				bind[1].is_null= 0;
				bind[1].length= 0;

				if (mysql_stmt_bind_param(stmt, bind) == 0)
				{
					if (mysql_stmt_execute(stmt) == 0)
					{
						if(mysql_stmt_affected_rows(stmt) == 1)
						{
							ret = true;
						}
					}
				}
				EFREE(binbuff);
			}
		}
		mysql_stmt_close(stmt);
	}
	return(ret);
}
예제 #25
0
static int test_bug16143(MYSQL *mysql)
{
  MYSQL_STMT *stmt;

  stmt= mysql_stmt_init(mysql);
  FAIL_IF(!stmt, mysql_error(mysql));

  /* Check mysql_stmt_sqlstate return "no error" */
  FAIL_UNLESS(strcmp(mysql_stmt_sqlstate(stmt), "00000") == 0, "Expected SQLstate 000000");

  mysql_stmt_close(stmt);

  return OK;
}
예제 #26
0
long PreparedStatement::Init(MYSQL *conn, string call)
{
    stmt = mysql_stmt_init(conn);
    if (!stmt)
    {
        printf("Could not initialize statement\n");
        exit(1);
    }
    int status = mysql_stmt_prepare(stmt,call.c_str(), call.length());
    test_stmt_error(stmt, status);
    connection = conn;
    
    return 0;
}
예제 #27
0
MYSQL_STMT *STDCALL 
DbUtil::mysqlSimplePrepare(const char *query)
{
  #ifdef DEBUG
    printf("Inside DbUtil::mysqlSimplePrepare\n");
  #endif
  MYSQL_STMT *my_stmt= mysql_stmt_init(this->getMysql());
  if (my_stmt && mysql_stmt_prepare(my_stmt, query, (unsigned long)strlen(query))){
    this->printStError(my_stmt,"Prepare Statement Failed");
    mysql_stmt_close(my_stmt);
    return NULL;
  }
  return my_stmt;
}
예제 #28
0
static int test_bad_union(MYSQL *mysql)
{
  MYSQL_STMT *stmt;
  int        rc;
  const char *query= "SELECT 1, 2 union SELECT 1";

  stmt= mysql_stmt_init(mysql);
  FAIL_IF(!stmt, mysql_error(mysql));
  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  FAIL_UNLESS(rc && mysql_errno(mysql) == 1222, "Error expected");

  mysql_stmt_close(stmt);
  return OK;
}
예제 #29
0
파일: test.cpp 프로젝트: longshadian/estl
bool selectDB_stmt()
{
    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(), "test", PORT,nullptr,0)) {
        printf("error mysql_real_connect\n");
        return false;
    }

    std::string sql = "select fid, fidx, fname, fdatetime, ftext, fdouble, fblob from txx where fid = ?";
    std::unique_ptr<MYSQL_STMT, MysqlStmtDestroy> mysql_stmt{mysql_stmt_init(&*mysql)};
    mysql_stmt_prepare(&*mysql_stmt, sql.data(), sql.size());

    std::unique_ptr<MYSQL_RES, MysqlResDestroy> mysql_res{mysql_store_result(&*mysql)};
    if (!mysql_res) {
        printf("error mysql_use_result\n");
        return false;
    }
    printf("query num: %d %d\n", (int)mysql_num_rows(&*mysql_res), (int)mysql_num_fields(&*mysql_res));

    MYSQL_ROW mysql_row = mysql_fetch_row(&*mysql_res);
    while (mysql_row) {
        printf("%s %s %s %s %s %s\n", mysql_row[0], mysql_row[1], mysql_row[2], mysql_row[3], mysql_row[4], mysql_row[5]);
        auto* lengths = mysql_fetch_lengths(&*mysql_res);
        const uint8_t* row_data = (const uint8_t*)mysql_row[6];
        auto row_len = lengths[6];
        std::vector<uint8_t> fblob{row_data, row_data + row_len};

        auto len = fblob.size()/sizeof(int32_t);
        const int32_t* p = (const int32_t*)fblob.data();
        for (size_t i = 0; i != len; ++i) {
            printf("\t\t val:%d\n", p[i]);
        }

        /*
        for (auto v : fblob) {
            printf("\t\t val:%d\n", (int)v);
            (void)v;
        }
        */

        mysql_row = mysql_fetch_row(&*mysql_res);
    }

    return true;
}
예제 #30
0
static int prepare(T C, const char *sql, int len, MYSQL_STMT **stmt) {
        if (! (*stmt = mysql_stmt_init(C->db))) {
                DEBUG("mysql_stmt_init -- Out of memory\n");
                C->lastError = CR_OUT_OF_MEMORY;
                return false;
        }
        if ((C->lastError = mysql_stmt_prepare(*stmt, sql, len))) {
                StringBuffer_clear(C->sb);
                StringBuffer_append(C->sb, "%s", mysql_stmt_error(*stmt));
                mysql_stmt_close(*stmt);
                *stmt = NULL;
                return false;
        }
        return true;
}