我已经通读了文档,并查看了示例,但是我仍然不知道如何在C++中将表赋给全局变量。我可能有点被宠坏了。我来自python,使用mysqldb将表分配给全局变量实际上是一件很简单的事情。
可以将表赋给要在mysqlpp类外部访问的全局变量吗?
例如,当编译下面的代码时,我得到错误: error:‘sched_recs’没有在这个作用域中声明
#include <mysql++.h>
#include <string>
#include <time.h>
using namespace std;
using namespace mysqlpp;
int SSE (const char* timeStr)
{
time_t sse;
struct tm tm;
strptime(timeStr, "%Y-%m-%d %H:%M:%S", &tm);
sse = mktime(&tm);
return (sse);
}
int main()
{
string table = "sched_recs";
time_t now, tt;
now = time(NULL);
try
{
// Connect to the sample database.
mysqlpp::Connection conn(false);
// databasename, host, username, password
if (conn.connect("dbname", "dbhost", "dbusername", "dbpasswd")) {
// Retrieve a subset of the sample stock table set up by resetdb
// and display it.
//stmt = "select datetime from %s", table
mysqlpp::Query query = conn.query("select * from sched_recs");
mysqlpp::StoreQueryResult sched_recs = query.store();
//if (mysqlpp::StoreQueryResult tableData = query.store()) {
////cout << "We have:" << endl;
//}
}
}
catch (Exception& e)
{
cerr << "Exception: " << e.what() << endl;
}
for (size_t i = 0; i < sched_recs.num_rows(); ++i) {
if (SSE(sched_recs[i][1]) - 60 * 3 < now && SSE(sched_recs[i][2]) > now)
{
cout << '\t' << sched_recs[i][1] << endl;
//system("at -f test.py '18:30' today");
}
}
}如果我将for循环移回到类中,那么一切都很好,但这是有限制的。这是唯一的方法吗?所有的例子看起来都是这样的。
发布于 2012-03-15 20:12:29
就像亚尼罗建议的那样。
尝试以下代码片段
#include <mysql++.h>
#include <string>
#include <time.h>
using namespace std;
using namespace mysqlpp;
int SSE (const char* timeStr)
{
time_t sse;
struct tm tm;
strptime(timeStr, "%Y-%m-%d %H:%M:%S", &tm);
sse = mktime(&tm);
return (sse);
}
int main()
{
string table = "sched_recs";
mysqlpp::StoreQueryResult sched_recs;
time_t now, tt;
now = time(NULL);
try
{
// Connect to the sample database.
mysqlpp::Connection conn(false);
// databasename, host, username, password
if (conn.connect("dbname", "dbhost", "dbusername", "dbpasswd")) {
// Retrieve a subset of the sample stock table set up by resetdb
// and display it.
//stmt = "select datetime from %s", table
mysqlpp::Query query = conn.query("select * from sched_recs");
sched_recs = query.store();
//if (mysqlpp::StoreQueryResult tableData = query.store()) {
////cout << "We have:" << endl;
//}
}
}
catch (Exception& e)
{
cerr << "Exception: " << e.what() << endl;
}
for (size_t i = 0; i < sched_recs.num_rows(); ++i) {
if (SSE(sched_recs[i][1]) - 60 * 3 < now && SSE(sched_recs[i][2]) > now)
{
cout << '\t' << sched_recs[i][1] << endl;
//system("at -f test.py '18:30' today");
}
}
}请注意,此示例和您发布的示例中唯一的区别是名为sched_recs的mysqlpp::StoreQueryResult变量声明的位置。
在此示例中,它在main的作用域中声明,而不是在try块的作用域中声明,因此在try块结束后,该变量的值仍在作用域中。
有关try和catch块作用域的更多信息,请参见Exception dangers and downsides。
https://stackoverflow.com/questions/9714653
复制相似问题