题
我已经通读了文档,并查看了示例,但我仍然不知道如何在 C++ 中将表分配给全局变量。我可能有点被宠坏了。我来自 python,使用 mysqldb 将表分配给全局变量确实是一件简单的事情。
是否可以将表分配给全局变量以便在 mysqlpp 类外部访问?
例如,当编译以下代码时,我收到错误:错误:“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 循环移回类中,那么一切都会正常工作,但这是有限制的。这是唯一的方法吗?所有的例子似乎都证明了这一点。
解决方案
正如雅尼罗建议的那样。
尝试以下代码片段
#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");
}
}
}
请注意,此示例与您发布的示例中的唯一区别是声明的位置 mysqlpp::StoreQueryResult
变量称为 sched_recs
.
在此示例中,它是在 main 的作用域中声明的,而不是在 try 块的作用域中声明的,因此在 try 块完成后,变量的值仍在作用域内。
有关 try 和 catch 块作用域的更多信息,请参阅 异常的危险和缺点.
不隶属于 StackOverflow