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

相关推荐
造火箭16 分钟前
安卓不同类型自动化测试介绍
android
吹什么轩3 小时前
MySQL:数据库基础
数据库·mysql
FluxDB3 小时前
用 Rust + GPUI 重做数据库客户端
数据库·mysql
Yyyyyy~3 小时前
【Mysql】增删查改操作
数据库·mysql
汪海游龙3 小时前
流式回复结尾的那一下闪:逐帧定位 Compose 聊天列表的三处布局跳动
android·性能优化·kotlin
BBmmo3 小时前
MySQL 里大小写不同的邮箱,为什么会撞上唯一索引?
mysql
专注仿真4 小时前
从「能跑通」到「能交付」:一套可直接落地的电商用户行为分析平台(Python + SQLite/MySQL + Streamlit 全栈源码与部署文档)
python·mysql·sqlite
1024奇点5 小时前
【仓颉语言入门 · 第二篇 第 10 课】
开发语言·数据库·ide·mysql·开源
2501_915909066 小时前
Ipa Guard 防护上架,混淆、重签名和回归测试怎么做
android·ios·小程序·https·uni-app·iphone·webview
码点6 小时前
Android ANR 全解析 与 traces 分析实战
android