C++ C++;MySQL,使用在同一类中的另一个函数中的一个函数中建立的连接
简单代码如下:C++ C++;MySQL,使用在同一类中的另一个函数中的一个函数中建立的连接,c++,mysql,connection,C++,Mysql,Connection,简单代码如下: class A{ MySQL *conn; int query; public: bool one(string fpServerName, string fpUserName, string fpPassword, string fpDatabase){ conn = mysql_init(&mysql); conn = mysql_real_connect(&mysql, fpServerName.c_str(), f
class A{
MySQL *conn;
int query;
public:
bool one(string fpServerName, string fpUserName, string fpPassword, string fpDatabase){
conn = mysql_init(&mysql);
conn = mysql_real_connect(&mysql, fpServerName.c_str(), fpUserName.c_str(), fpPassword.c_str(), fpDatabase.c_str(), 0, NULL, 0);
if (!conn)
return false;
else
return true;
}
two(string fpSQL){
query = mysql_query(conn, fpSQL.c_str());
}
A(){}
}
int main(){
A obj;
obj.one("127.0.0.1", "root", "", "users");
obj.two(fpSQL);
}
当我调用一个(“127.0.0.1”、“根”、“用户”)函数时,它连接到DB。现在我想使用conn-in-two(fpSQL),但不幸的是query=mysql_-query(conn,fpSQL.c_-str())中的程序崩溃;我有什么遗漏吗?谢谢您的建议。程序正在崩溃,因为您的conn变量为nullptr 尝试以下方式检查conn变量:
void two(string fpSQL){
if(nullptr!=conn){
query = mysql_query(conn, fpSQL.c_str());
}
}
int main(){
A obj;
if(obj.one("127.0.0.1", "root", "", "users")){
obj.two(fpSQL);
// Close connection here
}
}
另一件事是,函数one返回一个您没有检查的布尔值,以这种方式更改主函数:
void two(string fpSQL){
if(nullptr!=conn){
query = mysql_query(conn, fpSQL.c_str());
}
}
int main(){
A obj;
if(obj.one("127.0.0.1", "root", "", "users")){
obj.two(fpSQL);
// Close connection here
}
}
记住关闭主管道末端的连接