質問
ドキュメントを読み、例を見ていますが、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
変数の宣言の場所です。
このサンプルでは、TRYブロックの範囲ではなく、メインの範囲内で宣言されているため、TRYブロックが終了した後も変数の値は依然として範囲内です。
Try and Catch Blockスコープの詳細については、例外を参照してください。危険性とダウンサイド
所属していません StackOverflow