我编写了 c++ 类来连接 mysql 数据库:
.hpp 文件
#include <vector>
#include <string>
#include "mysql/mysql.h"
#ifndef _DATA
#define _DATA
class Database {
public:
string host;
string user;
string pwd;
string db;
MYSQL * connection;
MYSQL_RES *result;
MYSQL_ROW row;
Database(const string & host,
const string & user,
const string & pwd,
const string & db);
int createMysqlConnection();
};
#endif
.cpp 文件
#include "Database.hpp"
Database::Database(const string & host,
const string & user,
const string & pwd,
const string & db) :
mysqlHost(host),
mysqlUser(user),
mysqlPassword(pwd),
mysqlDBName(db)
{}
int Database::createMysqlConnection(){
MYSQL * connection;
connection = mysql_init(NULL);
if(!mysql_real_connect(connection, mysqlHost.c_str(), mysqlUser.c_str(),
mysqlPassword.c_str(), mysqlDBName.c_str(),
0, NULL, 0)){
fprintf(stderr, "Connection to database failed: %s\n",
mysql_error(connection));
return EXIT_FAILURE;
}
cout << "connected to mysql" << endl;
};
当我试图从主函数或不同的类访问连接变量时,我总是得到一个错误,比如变量 'connection is not declared in this scope。我尝试使用友元类或继承来指向连接变量,但它不起作用。我认为我的语法有问题。
这是我如何尝试从不同类指向此变量的示例:
Class risk: public Database {
public:
vector<sting> parameter;
Datasabse.connection;
etc....
}