c++ - MySQL 和可变参数

标签 c++ mysql variadic-functions

我有以下存储在缓冲区中的查询,然后使用我自己的 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;
}

我知道可变参数,并尝试遵循此处的示例 (Variable number of arguments in C++?),但我不是简单地尝试读取可变参数,而是将它们包含在查询中,这显然对我来说很麻烦。

欢迎任何想法,谢谢。

最佳答案

您需要一个准备好的语句,如下所示

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 和可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260414/

相关文章:

c++ - Cucumber-cpp 运行示例所需的软件

c++ - 在特定对象实例上调用 C++ 函数指针

android - OpenGL ES 2.0 通过共享 C++ 代码在 ios 和 android 上进行抗锯齿或平滑处理

MySQL 替换为 Char 函数

c++ - 不知道为什么我会收到关于 std::size_t 不包含参数包的编译错误

c++ - 向 Wt WTable 小部件添加网格线

php - 如何有效实现新闻通讯系统以防止重复发送电子邮件?

mysql - SQL Group By Column 没有一个值

时间:2019-05-17 标签:c++variadicfunction: What is the best way to replace?

c++ - 模板化 boost::bind 以自动处理成员函数的多个参数