简体   繁体   English

从mysql连接器C ++ API获取当前连接

[英]get current connection from mysql connector c++ api

Im using the mysql connector c++ api and I made, that my program connect to the database after I execute it. 我使用的是mysql连接器c ++ api,我将程序执行后连接到数据库。

But now I have to do querys on other cpp files. 但是现在我必须对其他cpp文件进行查询。

Should I open a new connection and close it every time I do a query or should I keep that one connection? 我应该在每次查询时打开一个新连接并关闭它,还是应该保留一个连接?

And if its better to keep one connection, then how can I get the current connection on other cpp files? 如果保持一个连接更好,那么如何在其他cpp文件上获得当前连接呢?

main on 1.cpp 主要在1.cpp

int AuthServerMain(int argc, _TCHAR* argv[])
{
    sql::mysql::MySQL_Driver *driver;
    sql::Connection * con;
    driver = sql::mysql::get_mysql_driver_instance();
    con = driver->connect("tcp://ip:3306", "root", "password");
    con->setSchema("dbo");
}

now my problem is the "con" 现在我的问题是“骗局”

if I write on 2.cpp 如果我在2.cpp上写

sql::Statement * stmt;
sql::ResultSet * resset;
stmt = con->createStatement();

then "con" is red underlined because he cant find it. 然后“骗子”用红色下划线标出,因为他找不到。 How can I do that he can find "con"? 我该怎么办,他才能找到“骗子”?

Why would you not make a database class, which has the connection varaible inside it. 您为什么不制作一个database类,其中的连接可变。 Then you could just pass this class around the .cpp files where you need it. 然后,您可以在需要的.cpp文件中传递此类。 You could make a function like database::excetute(std::string s) or even overload the << operator , so your code in the other .cpp files are clean. 您可以创建类似于database::excetute(std::string s)的函数,甚至可以重载<< operator ,因此其他.cpp文件中的代码是干净的。

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

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