我将以下查询存储在缓冲区中,然后使用自己的conn.executeQuery()执行。
char buffer[QUERY_MAX];
snprintf(buffer, QUERY_MAX, "SELECT * FROM players WHERE player_id = %d", 1);
conn.executeQuery(buffer);
虽然这很好用,但我想知道是否可以将其简化为类似于...
conn.executeQuery("SELECT * FROM players WHERE player_id = "%d", 1);
我的功能:
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;
}
我知道varargs,并尝试遵循此处的示例(Variable number of arguments in C++?),但我不是简单地尝试读取varargs,而是将它们包括在查询中,这对我来说显然很麻烦。
任何想法都欢迎,谢谢。
最佳答案
您需要准备的语句,如下所示
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);
关于c++ - MySQL和varargs,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45260414/