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

相关推荐
程序员夏洛5 小时前
MySQL 中 count(*)、count(1) 和 count(字段名) 有什么区别?
数据库·mysql
l1258656 小时前
# RAG向量数据库优化实战:HNSW索引调参与生产级性能设计
数据库·python·mysql·langchain
梦Arrebol6 小时前
Mysql内容及相关实验
数据库·mysql
OceanWaves19937 小时前
mysql 8.0.32 磁盘爆满,清理从库日志
数据库·mysql
又见情义7 小时前
RK3568 Android 13 驱动适配实战:从零开始让SDK在自己的板子上跑起来
android·arm开发·驱动开发
clorinda8 小时前
MySQL 入门笔记:DQL 基础查询与常用函数
adb
JavaPub-rodert9 小时前
Go 后台如何同时兼容 MySQL、PostgreSQL、SQLite 和 SQL Server?从 ShiyuAdmin 看 GORM 多数据库适配
数据库·mysql·postgresql·golang·javapub·王仕宇
明雨-开发9 小时前
Android打包时候Execution failed for task ‘:launcher:lintVitalAnalyzeRelease‘.
android
游戏开发爱好者89 小时前
开心上架是什么,一站式 Apple 开发者工作台总览
android·小程序·https·uni-app·iphone·webview
Android-Flutter9 小时前
android kotlin launch 源码分析
android·kotlin