linux cc++ 调mysql_stmt_prepare实现select code from ucs2_mapmap where code= code的值和长度都只知道code=text给出实现
下面是一个示例代码,展示如何在Linux下使用C/C++调用mysql_stmt_prepare函数来实现select code from ucs2_map.map where code='?'的查询:
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
MYSQL *conn;
MYSQL_STMT *stmt;
MYSQL_BIND bind[1];
unsigned long code_length;
char code[10] = "text";
conn = mysql_init(NULL);
if (conn == NULL) {
fprintf(stderr, "mysql_init() failed\n");
return 1;
}
if (!mysql_real_connect(conn, "localhost", "user", "password",
"database", 0, NULL, 0)) {
fprintf(stderr, "mysql_real_connect() failed: %s\n", mysql_error(conn));
mysql_close(conn);
return 1;
}
stmt = mysql_stmt_init(conn);
if (stmt == NULL) {
fprintf(stderr, "mysql_stmt_init() failed\n");
mysql_close(conn);
return 1;
}
if (mysql_stmt_prepare(stmt, "SELECT code FROM ucs2_map.map WHERE code=?", strlen("SELECT code FROM ucs2_map.map WHERE code=?")) != 0) {
fprintf(stderr, "mysql_stmt_prepare() failed: %s\n", mysql_stmt_error(stmt));
mysql_stmt_close(stmt);
mysql_close(conn);
return 1;
}
memset(bind, 0, sizeof(bind));
bind[0].buffer_type = MYSQL_TYPE_STRING;
bind[0].buffer = code;
bind[0].buffer_length = sizeof(code);
bind[0].length = &code_length;
if (mysql_stmt_bind_param(stmt, bind) != 0) {
fprintf(stderr, "mysql_stmt_bind_param() failed: %s\n", mysql_stmt_error(stmt));
mysql_stmt_close(stmt);
mysql_close(conn);
return 1;
}
if (mysql_stmt_execute(stmt) != 0) {
fprintf(stderr, "mysql_stmt_execute() failed: %s\n", mysql_stmt_error(stmt));
mysql_stmt_close(stmt);
mysql_close(conn);
return 1;
}
MYSQL_BIND result_bind[1];
char result_code[10];
unsigned long result_code_length;
memset(result_bind, 0, sizeof(result_bind));
result_bind[0].buffer_type = MYSQL_TYPE_STRING;
result_bind[0].buffer = result_code;
result_bind[0].buffer_length = sizeof(result_code);
result_bind[0].length = &result_code_length;
if (mysql_stmt_bind_result(stmt, result_bind) != 0) {
fprintf(stderr, "mysql_stmt_bind_result() failed: %s\n", mysql_stmt_error(stmt));
mysql_stmt_close(stmt);
mysql_close(conn);
return 1;
}
if (mysql_stmt_fetch(stmt) != 0) {
fprintf(stderr, "mysql_stmt_fetch() failed: %s\n", mysql_stmt_error(stmt));
mysql_stmt_close(stmt);
mysql_close(conn);
return 1;
}
printf("Result: %.*s\n", (int)result_code_length, result_code);
mysql_stmt_close(stmt);
mysql_close(conn);
return 0;
}
在上面的示例代码中,需要根据实际情况将localhost、user、password和database替换为正确的数据库连接信息。
首先,使用mysql_init函数初始化一个MySQL连接对象,然后使用mysql_real_connect函数连接到数据库。
接下来,使用mysql_stmt_init函数初始化一个MySQL语句对象,使用mysql_stmt_prepare函数准备查询语句。
在绑定参数时,使用MYSQL_BIND结构体定义一个参数绑定对象,将code字符串绑定到第一个参数上。
然后,使用mysql_stmt_bind_param函数将参数绑定到语句对象上。
执行查询时,使用mysql_stmt_execute函数执行语句。
接着,使用mysql_stmt_bind_result函数绑定结果集对象,将查询结果绑定到result_code字符串上。
最后,使用mysql_stmt_fetch函数获取查询结果,并打印出来。
最后,使用mysql_stmt_close函数关闭语句对象,并使用mysql_close函数关闭连接。
请注意,上述示例代码仅供参考,实际使用时需要根据实际情况进行适当的修改和错误处理
原文地址: https://www.cveoy.top/t/topic/iN4v 著作权归作者所有。请勿转载和采集!