当我使用pqxx创建到psql数据库的连接数组时,连接创建成功,并且它们在该数组中。但是,当我要使用一个连接时,会出现以下错误。我还介绍了创建数组的方式。谁能告诉我原因。
for(int i=0;i<10;i++)
{
connection c("dbname=test user=postgres password=abc123\
hostaddr=127.0.0.1 port=5432");
conList[i]=&c;
}
for (int j=0;j<10;j++)
{
cout<<conList[j]->is_open()<<endl; // this returns 0
}
conList[0]->activate(); // at this point it gives the following error
抛出'pqxx :: broken_connection'实例之后调用终止方法what():与数据库的连接失败中止
您正在将局部变量的地址存储c
在中conList
,在第一次for
循环之后,那些局部变量被释放,仅conList
存储悬空指针,对悬空指针的调用函数调用具有未定义的行为。
for(int i=0;i<10;i++)
{
connection c("dbname=test user=postgres password=abc123\
hostaddr=127.0.0.1 port=5432");
conList[i]=&c; // c is local variable
} // c is released here
for (int j=0;j<10;j++)
{
cout<<conList[j]->is_open()<<endl; // undefined behavior
}
conList[0]->activate(); // undefined behavior
考虑下面的变化?
存储值而不是指针 conList
for(int i=0;i<10;i++)
{
connection c("dbname=test user=postgres password=abc123\
hostaddr=127.0.0.1 port=5432");
conList[i] = c; // make a copy of c
}
for (int j=0;j<10;j++)
{
cout<<conList[j].is_open()<<endl;
}
conList[0].activate();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句