示例#1
0
bool Extractor::extract(std::size_t pos, Poco::Data::BLOB& val)
{
	if (_metadata.columnsReturned() <= pos)
        throw MySQLException("Extractor: attempt to extract more paremeters, than query result contain");

    if (_metadata.isNull(static_cast<Poco::UInt32>(pos)))
        return false;

	if (_metadata.metaColumn(static_cast<Poco::UInt32>(pos)).type() != Poco::Data::MetaColumn::FDT_BLOB)
		throw MySQLException("Extractor: not a blob");

  unsigned long length= 0;
  MYSQL_BIND bind = { 0 };
  bind.buffer= 0;
  bind.buffer_length= 0;
  bind.length= &length;
  if ( ! _stmt.fetchColumn(pos, &bind) )
    return false;

  std::vector<char> data(length);
  bind.buffer = &data[0];
  bind.buffer_length= length;
  if ( ! _stmt.fetchColumn(pos, &bind) )
    return false;

  val.assignRaw(&data[0], length);
	return true;
}
void MySQLPreparedStatement::doQuery()
{
    checkClosed();
    MYSQL* mysql = mysqlConn->getMySQLHandle();

    if (mysql_stmt_bind_param(stmt, bind))
        throw MySQLException("MySQLPreparedStatement::doQuery, mysql_stmt_bind_param error",mysql);

    if (mysql_stmt_execute(stmt))
        throw MySQLException("MySQLPreparedStatement::doQuery, mysql_stmt_execute error",mysql);
}
示例#3
0
bool Extractor::extract(std::size_t pos, std::string& val)
{
	if (_metadata.columnsReturned() <= pos)
        throw MySQLException("Extractor: attempt to extract more paremeters, than query result contain");

    if (_metadata.isNull(static_cast<Poco::UInt32>(pos)))
        return false;

	if (_metadata.metaColumn(static_cast<Poco::UInt32>(pos)).type() != Poco::Data::MetaColumn::FDT_STRING)
		throw MySQLException("Extractor: not a string");

	val.assign(_metadata.rawData(pos), _metadata.length(pos));
	return true;
}
bool Extractor::extract(std::size_t pos, Poco::Data::CLOB& val)
{
	if (_metadata.columnsReturned() <= pos)
		throw MySQLException("Extractor: attempt to extract more paremeters, than query result contain");
	
	if (_metadata.isNull(static_cast<Poco::UInt32>(pos)))
	return false;
	
	if (_metadata.metaColumn(static_cast<Poco::UInt32>(pos)).type() != Poco::Data::MetaColumn::FDT_BLOB)
		throw MySQLException("Extractor: not a blob");
	
	val.assignRaw(reinterpret_cast<const char*>(_metadata.rawData(pos)), _metadata.length(pos));
	return true;
}
示例#5
0
void MySQLStatement::checkClosed()
{
    if (closed) {
        MYSQL* mysql = mysqlConn->getMySQLHandle();
        throw MySQLException("MySQLStatement::checkClosed, statement closed",mysql);
    }
}
示例#6
0
文件: Extractor.cpp 项目: 12307/poco
bool Extractor::extract(std::size_t pos, std::string& val)
{
	if (_metadata.columnsReturned() <= pos)
		throw MySQLException("Extractor: attempt to extract more parameters, than query result contain");
	
	if (_metadata.isNull(static_cast<Poco::UInt32>(pos)))
	return false;
	
	//mysql reports TEXT types as FDT_BLOB when being extracted
	MetaColumn::ColumnDataType columnType = _metadata.metaColumn(static_cast<Poco::UInt32>(pos)).type();
	if (columnType != Poco::Data::MetaColumn::FDT_STRING && columnType != Poco::Data::MetaColumn::FDT_BLOB)
		throw MySQLException("Extractor: not a string");
		
	val.assign(reinterpret_cast<const char*>(_metadata.rawData(pos)), _metadata.length(pos));
	return true;
}
示例#7
0
void MySQLStatement::doQuery(const char* sql, uint32 length)
{
    checkClosed();
    MYSQL* mysql = mysqlConn->getMySQLHandle();

    if (mysql_real_query(mysql, sql, static_cast<unsigned long>(length)) && mysql_errno(mysql))
        throw MySQLException("MySQLStatement::doQuery, mysql_real_query error",mysql);
}
示例#8
0
MySQL::MySQL(const std::string &host, const std::string &user, const std::string &pass, const std::string &db, short p = 0) :
	user(user), pass(pass), host(host), db(db), port(p)
{
	printf("MySQL client version: %s\n", mysql_get_client_info());

	// Create the MySQL object
	this->con = mysql_init(NULL);

	if (!con)
		throw MySQLException("Failed to create a mysql object!");

	// Authenticate to the MySQL database
	if (!this->DoConnection())
		throw MySQLException(tfm::format("%s (%d)", mysql_error(this->con), mysql_errno(this->con)));

	printf("Connected to %s: %lu\n", host.c_str(), mysql_thread_id(this->con));
}
示例#9
0
int MySQLStatement::executeUpdate(const std::string& sql)
{
    doQuery(sql.c_str(), sql.length());
    MYSQL* mysql = mysqlConn->getMySQLHandle();
    if (mysql_field_count(mysql) > 0) { // check if the query return something
        throw MySQLException("MySQLStatement::executeUpdate, error the return something",mysql);
    }

    return static_cast<int>(mysql_affected_rows(mysql));
}
bool Extractor::isNull(std::size_t col, std::size_t row)
{
	poco_assert(row == POCO_DATA_INVALID_ROW);

	if (_metadata.columnsReturned() <= col)
		throw MySQLException("Extractor: attempt to extract more paremeters, than query result contain");

	if (_metadata.isNull(static_cast<Poco::UInt32>(col)))
		return true;

	return false;
}
示例#11
0
ResultSet* MySQLStatement::getResultSet()
{
    checkClosed();
    MYSQL* mysql = mysqlConn->getMySQLHandle();
    MYSQL_RES* res = NULL;

    res = mysql_store_result(mysql);

    if (!res) {
        // check possible error
        if (mysql_errno(mysql) !=0) // an error occurred
            throw MySQLException("MySQLStatement::getResultSet mysql_store_result error",mysql);

        // INSERT, UPDATE, DELETE : no result set
        return NULL;
    }

    return new MySQLResultSet(this, res);
}
示例#12
0
void SessionImpl::open(const std::string& connect)
{
	if (connect != connectionString())
	{
		if (isConnected())
			throw InvalidAccessException("Session already connected");

		if (!connect.empty())
			setConnectionString(connect);
	}

	poco_assert_dbg (!connectionString().empty());

	_handle.init();
	
	unsigned int timeout = static_cast<unsigned int>(getLoginTimeout());
	_handle.options(MYSQL_OPT_CONNECT_TIMEOUT, timeout);

	std::map<std::string, std::string> options;

	// Default values
	options["host"] = "localhost";
	options["port"] = "3306";
	options["user"] = "";
	options["password"] = "";
	options["db"] = "";
	options["compress"] = "";
	options["auto-reconnect"] = "";
	options["secure-auth"] = "";
	options["character-set"] = "utf8";

	const std::string& connString = connectionString();
	for (std::string::const_iterator start = connString.begin();;) 
	{
		std::string::const_iterator finish = std::find(start, connString.end(), ';');
		std::string::const_iterator middle = std::find(start, finish, '=');

		if (middle == finish)
			throw MySQLException("create session: bad connection string format, can not find '='");

		options[copyStripped(start, middle)] = copyStripped(middle + 1, finish);

		if ((finish == connString.end()) || (finish + 1 == connString.end())) break;

		start = finish + 1;
	} 

	if (options["user"].empty())
		throw MySQLException("create session: specify user name");

	const char * db = NULL;
	if (!options["db"].empty())
		db = options["db"].c_str();

	unsigned int port = 0;
	if (!NumberParser::tryParseUnsigned(options["port"], port) || 0 == port || port > 65535)
		throw MySQLException("create session: specify correct port (numeric in decimal notation)");

	if (options["compress"] == "true")
		_handle.options(MYSQL_OPT_COMPRESS);
	else if (options["compress"] == "false")
		;
	else if (!options["compress"].empty())
		throw MySQLException("create session: specify correct compress option (true or false) or skip it");

	if (options["auto-reconnect"] == "true")
		_handle.options(MYSQL_OPT_RECONNECT, true);
	else if (options["auto-reconnect"] == "false")
		_handle.options(MYSQL_OPT_RECONNECT, false);
	else if (!options["auto-reconnect"].empty())
		throw MySQLException("create session: specify correct auto-reconnect option (true or false) or skip it");

	if (options["secure-auth"] == "true")
		_handle.options(MYSQL_SECURE_AUTH, true);
	else if (options["secure-auth"] == "false")
		_handle.options(MYSQL_SECURE_AUTH, false);
	else if (!options["secure-auth"].empty())
		throw MySQLException("create session: specify correct secure-auth option (true or false) or skip it");

	if (!options["character-set"].empty())
		_handle.options(MYSQL_SET_CHARSET_NAME, options["character-set"].c_str());

	// Real connect
	_handle.connect(options["host"].c_str(), 
			options["user"].c_str(), 
			options["password"].c_str(), 
			db, 
			port);

	addFeature("autoCommit", 
		&SessionImpl::autoCommit, 
		&SessionImpl::isAutoCommit);

	_connected = true;
}
示例#13
0
MySQL_Result MySQL::Query(const std::string &query)
{
	this->mtx.lock();
	// Form our object
	MySQL_Result res;
	MYSQL_RES *result = nullptr;
	MYSQL_ROW row;
	int cnt = 0;

	printf("***** EXECUTING QUERY ******\n\n");
	tfm::printf("QUERY: \"%s\"\n\n", query);

	// If we fail to connect, just return an empty query.
	if (!this->con)
		if (!this->CheckConnection())
			goto exit;

	// Run the query
	if (mysql_query(this->con, query.c_str()))
	{
		std::string msg = tfm::format("%s (%d)\n", mysql_error(this->con), mysql_errno(this->con));
		this->mtx.unlock();
		throw MySQLException(msg);
	}

	// Store the query result
	result = mysql_store_result(this->con);
	if (result == NULL && mysql_errno(this->con) == 0)
		goto exit;
	else if (result == NULL)
	{
		std::string msg = tfm::format("%s (%d)\n", mysql_error(this->con), mysql_errno(this->con));
		this->mtx.unlock();
		throw MySQLException(msg);
	}

	// Get total columns/fields w/e
	res.fields = mysql_num_fields(result);

	printf("Iteraing rows, we have %d columns to look at\n", res.fields);
	// Loop through the MySQL objects and create the array for the query result
	while ((row = mysql_fetch_row(result)))
	{
		// Create a vector of std::strings for rows the size of the number of columns we have
		std::vector<std::string> vrow;
		vrow.reserve(res.fields);

		// Loop over those columns and push them into the vector
		printf("Row[%d]: ", cnt);
		for (int i = 0; i < res.fields; ++i)
		{
			std::string index = row[i];
			vrow.push_back(index);
			tfm::printf("%s ", index);
		}
		printf("\n");

		// Add to our result
		res.rows[cnt++] = vrow;
	}

	if (res.rows.empty())
		printf("Empty set\n");

	mysql_free_result(result);

exit:

	printf("\n***** QUERY COMPLETE ******\n");
	this->mtx.unlock();

	return res;
}
ResultSet* MySQLPreparedStatement::executeQuery(const std::string& sql)
{
    throw MySQLException("MySQLPreparedStatement prepared statement doesn't support this operation executeQuery(const std::string& sql)");
    return NULL;
}
int MySQLPreparedStatement::executeUpdate(const std::string& sql)
{
    throw MySQLException("MySQLPreparedStatement prepared statement doesn't support this operation executeUpdate(const std::string& sql)");
    return 0;
}
void MySQLPreparedStatement::checkValidity(const uint8 idx)
{
    if (idx == 0 || idx > paramCount)
        throw MySQLException("MySQLPreparedStatement::checkValidity(), invalid index");
}
示例#17
0
SessionImpl::SessionImpl(const std::string& connectionString) : _mysql(0), _connected(false), _inTransaction(0)
{
    addProperty("insertId",
                &SessionImpl::setInsertId,
                &SessionImpl::getInsertId);

    std::map<std::string, std::string> options;

    // Default values
    options["host"] = "localhost";
    options["port"] = "3306";
    options["user"] = "";
    options["password"] = "";
    options["db"] = "";
    options["compress"] = "";
    options["auto-reconnect"] = "";

    //
    // Parse string
    //

    for (std::string::const_iterator start = connectionString.begin();;)
    {
        // find next ';'
        std::string::const_iterator finish = std::find(start, connectionString.end(), ';');

        // find '='
        std::string::const_iterator middle = std::find(start, finish, '=');

        if (middle == finish)
        {
            throw MySQLException("create session: bad connection string format, can not find '='");
        }

        // Parse name and value, skip all spaces
        options[copyStripped(start, middle)] = copyStripped(middle + 1, finish);

        if (finish == connectionString.end())
        {
            // end of parse
            break;
        }

        // move start position after ';'
        start = finish + 1;
    }

    //
    // Checking
    //

    if (options["user"] == "")
    {
        throw MySQLException("create session: specify user name");
    }

    if (options["db"] == "")
    {
        throw MySQLException("create session: specify database");
    }

    unsigned int port = 0;
    if (!NumberParser::tryParseUnsigned(options["port"], port) || 0 == port || port > 65535)
    {
        throw MySQLException("create session: specify correct port (numeric in decimal notation)");
    }

    //
    // Options
    //

    if (options["compress"] == "true")
    {
        _mysql.options(MYSQL_OPT_COMPRESS);
    }
    else if (options["compress"] == "false")
    {
        // do nothing
    }
    else if (options["compress"] != "")
    {
        throw MySQLException("create session: specify correct compress option (true or false) or skip it");
    }

    if (options["auto-reconnect"] == "true")
    {
        _mysql.options(MYSQL_OPT_RECONNECT, true);
    }
    else if (options["auto-reconnect"] == "false")
    {
        _mysql.options(MYSQL_OPT_RECONNECT, false);
    }
    else if (options["auto-reconnect"] != "")
    {
        throw MySQLException("create session: specify correct auto-reconnect option (true or false) or skip it");
    }

    //
    // Real connect
    //

    _mysql.connect(
        options["host"].c_str(),
        options["user"].c_str(),
        options["password"].c_str(),
        options["db"].c_str(),
        port);

    _connected = true;
}
void MySQLPreparedStatement::checkClosed()
{
    if (closed)
        throw MySQLException("MySQLPreparedStatement::checkClosed() : statement closed");
}