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

相关推荐
2501_916008899 小时前
全面介绍Fiddler、Wireshark、HttpWatch、SmartSniff和firebug抓包工具功能与使用
android·ios·小程序·https·uni-app·iphone·webview
玉梅小洋10 小时前
Windows 10 Android 构建配置指南
android·windows
Libraeking11 小时前
视觉篇:Canvas 自定义绘图与高级动画的华丽圆舞曲
android·经验分享·android jetpack
Fushize12 小时前
多模块架构下的依赖治理:如何避免 Gradle 依赖地狱
android·架构·kotlin
Jomurphys13 小时前
Kotlin - 类型别名 typealias
android·kotlin
Haha_bj13 小时前
Flutter ——flutter_screenutil 屏幕适配
android·ios
Haha_bj13 小时前
Flutter ——device_info_plus详解
android·flutter·ios
前端小伙计13 小时前
Android/Flutter 项目统一构建配置最佳实践
android·flutter
Mr_sun.15 小时前
Day09——入退管理-入住-2
android·java·开发语言
ujainu16 小时前
告别杂乱!Flutter + OpenHarmony 鸿蒙记事本的标签与分类管理(三)
android·flutter·openharmony