繁体   English   中英

是否可以在 C++ 代码中从 mysql 函数返回连接对象?

[英]Is it possible to return the connection object from mysql function in C++ code?

错误:'sql' 没有命名类型 sql::Connection connect_mysql(); 有没有办法可以从这个函数返回连接对象? 我知道在 C 中返回连接对象,但在 C++ 中不会发生。
编辑版本:connect_mysql() 的返回类型已更改为 sql::Connection * 。 之前它是 sql::Connection。

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include<mysql/mysql.h>
#include<cppconn/driver.h>
#include<cppconn/exception.h>
#include<cppconn/resultset.h>
#include<cppconn/statement.h>
sql::Connection * connect_mysql();    


       int main()
       {
            sql::Connection *con;
            con = connect_mysql();
            return 0;
       }



      sql::Connection * connect_mysql()
        {
            cout << "CONNECTING DATABASE..............."<<endl;
            try{
                    cout<<"inside try while connecting to mysql"<<endl;
                    sql::Driver *driver;
                    sql::Connection *con;
                    sql::Statement *stmt;
                    sql::ResultSet *res;
                    driver = get_driver_instance();
                    con = driver->connect("localhost","root","Aricent@123");
                   con->setSchema( "COE" );                            
                    stmt = con->createStatement();                           
                    res = stmt->executeQuery( "show tables" );
                    while( res->next() )
                    {
                            cout<<"MYSQL replies:"<<endl;
                            cout<<res->getInt(1);
                            cout<<res->getString(1)<<endl;
                    }
           } 
        catch( exception e )
            {

                    cout << "# ERR: SQLException in " << __FILE__;                   
                    cout << "# ERR: ";
                    cout << " (MySQL error code: ";
                    cout << ", SQLState: ";
            }
            return con;
        }

这不是一个对象,它是一个指针。 尝试这个

sql::Connection* connect_mysql()
{
    ...
}

另一个错误是缺少connect_mysql原型。 你应该有这样的东西

   sql::Connection* connect_mysql(); // prototype

   int main()
   {
        sql::Connection *con;
        con = connect_mysql();
        ...

但是让我对您的错误消息感到困惑的是,它指的是sql::Connection* connect_mysql()但显然在sql::Connection *con;行中使用了相同的类型sql::Connection *con; 没问题。 如果您有任何其他错误消息或警告,请一并发布。

不需要说明为获得编译器错误消息的帮助,您应该发布确切的代码、确切的错误消息以及所有这些。

我不是 mysql 专家,但我想知道您是否需要头文件#include <cppconn/connection.h>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM