0

I have the following query that is stored in buffer, and then is executed using my own conn.executeQuery().

char buffer[QUERY_MAX];
snprintf(buffer, QUERY_MAX, "SELECT * FROM players WHERE player_id = %d", 1);
conn.executeQuery(buffer);

While this works fine, I wonder if it can be simplified as something similar to...

conn.executeQuery("SELECT * FROM players WHERE player_id = "%d", 1);

My function:

bool SQLConnection::executeQuery(const char *query)
{ 
// Validate connection.
if (!m_connected)
    return false;  

// Execute the query
int status = mysql_query(&m_conn, query);

if (status != 0) {
    sprintf(m_errorMessage, "Error: %s", mysql_error(&m_conn)); 
    return false;
}

// Store the result
m_result = mysql_store_result(&m_conn);

return true;
}

I'm aware of varargs, and tried to follow the example here (Variable number of arguments in C++?), but I'm not simply trying to read the varargs, but to include them in the query, which is apparently troublesome for me.

Any thoughts are welcomed, thanks.

1 Answer 1

1

You need a prepared statement instead, like the following

MYSQL_STMT *stmt;
MYSQL_BIND params[1 /* Here it will be the number of arguments */];
MYSQL_BIND result[1 /* Here it will be the number of columns in the result row */];
int value;
const char *query;
int id;

memset(params, 0, sizeof params);
memset(result, 0, sizeof result);
// Assuming `mysql' is an initialized MYSQL object
stmt = mysql_stmt_init(mysql);
if (stmt == NULL)
    return
// `SELECT ID' just to illustrate how you can select an integer
//             value
query = "SELECT ID FROM players WHERE player_id = ?";
if (mysql_stmt_prepare(stmt, query, strlen(query)) != 0)
    goto error;
value = 1;

result[0].buffer_type = MYSQL_TYPE_LONG;
result[0].buffer = &id;

params[0].buffer_type = MYSQL_TYPE_LONG;
params[0].buffer = &value;
if (mysql_stmt_bind_param(stmt, params) != 0)
    goto error;
if (mysql_stmt_bind_result(stmt, result) != 0)
    goto error;
if (mysql_stmt_execute(stmt) != 0)
    goto error;
if (mysql_stmt_fetch(stmt) != 0)
    goto error;
// Now all the columns are in the buffers of `result'
// or the bound variables (which is why we pass their address)
fprintf(stdout, "%d\n", id);

error:

mysql_stmt_close(stmt);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.