mysql 示例验证demo

确保引入了正确的头文件:

在 MySQL C++ Connector 中,ResultSet 和 Statement 类型的声明需要包含相关的头文件。你需要包括 resultset.h 和 statement.h。

更新代码:

你需要确保程序正确地包含了这些头文件,并且按照正确的顺序使用它们。

更新后的代码:

cpp 复制代码
cpp
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>  // 包含Statement头文件
#include <cppconn/resultset.h>  // 包含ResultSet头文件
#include <iostream>

int main() {
    try {
        // 创建 MySQL 驱动实例
        sql::mysql::MySQL_Driver *driver;
        sql::Connection *con;

        // 获取 MySQL 驱动
        driver = sql::mysql::get_mysql_driver_instance();

        // 连接到数据库
        con = driver->connect("tcp://127.0.0.1:3306", "monitor_user", "your_password");

        // 选择数据库
        con->setSchema("switch_commands");

        // 创建查询语句
        sql::Statement *stmt = con->createStatement();
        sql::ResultSet *res = stmt->executeQuery("SELECT * FROM command_mapping");

        // 输出查询结果
        while (res->next()) {
            std::cout << "Command: " << res->getString("command_input") 
                      << ", Mapped Command: " << res->getString("mapped_command")
                      << ", Description: " << res->getString("description")
                      << ", Action Type: " << res->getString("action_type") 
                      << std::endl;
        }

        // 清理资源
        delete res;
        delete stmt;
        delete con;
    } catch (sql::SQLException &e) {
        std::cerr << "Error connecting to MySQL: " << e.what() << std::endl;
    }

    return 0;
}

关键更新:

包含必要的头文件:

#include <cppconn/statement.h>:声明 Statement 类。

#include <cppconn/resultset.h>:声明 ResultSet 类。

确保头文件顺序正确:

mysql_driver.h 和 mysql_connection.h 是基础的 MySQL 连接头文件,其他的具体类型(如 Statement 和 ResultSet)需要在后续明确引用。

重新编译代码

使用以下命令重新编译你的代码:

cpp 复制代码
g++ -o mysql_example mysql_example.cpp -lmysqlcppconn

运行代码

编译成功后,运行程序:

./mysql_example

如果数据库连接成功,并且 command_mapping 表中有数据,你将看到类似的输出:

cpp 复制代码
yaml
Command: dis vlan, Mapped Command: show vlan brief, Description: 查询VLAN信息, Action Type: show
Command: dis ip, Mapped Command: show ip address, Description: 查询IP地址信息, Action Type: show

常见问题

ResultSet 类型未声明:如果你仍然看到类似 ResultSet 未声明的错误,确保已经安装了 libmysqlcppconn-dev,并且确保正确包含了相应的头文件。

链接错误:确保在编译时正确链接了 MySQL C++ Connector 库。-lmysqlcppconn 是必需的

相关推荐
阿巴斯甜8 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker8 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95279 小时前
Andorid Google 登录接入文档
android
黄林晴11 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇1 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_1 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android