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 是必需的

相关推荐
平头哥AI3 小时前
Day 22 _ 包装错误别丢链_%w、errors.Is 与 errors.As
android·服务器·学习·golang·go
聚美智数3 小时前
图片广告检测-图片审核-图片广告识别-图像广告检测
android
早睡早起身体好1236 小时前
用 XGrammar 约束大模型工具调用:解决参数为空的问题
android·人工智能·神经网络·机器学习·自然语言处理·vllm
服务端相声演员6 小时前
in子查询的执行可能被优化为连接查询
mysql
大佐不会说日语~8 小时前
Android 16 下 uni-app APP 提示“网络连接失败”的排障与修复
android·uni-app
2501_915106329 小时前
苹果App Store上架费用及流程全面解析
android·ios·小程序·https·uni-app·iphone·webview
写后端的胖头鱼10 小时前
【高频面试题】深分页问题
数据库·mysql·数据库优化·深分页
YF021111 小时前
Android 16系统App开机自启动方案
android
hm宋11 小时前
安卓手机卡顿优化 —— 背景与使用指南
android
OxYGC12 小时前
[Android] [WatchOS]智能手表第一篇: 实用工具与应用推荐
android·智能手表