gpt4 book ai didi

c++ - c++连接数据库

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:41 27 4
gpt4 key购买 nike

在 php 中,我创建了一个打开到数据库的连接的配置文件,然后我在我的所有其他文件中使用该文件,以便也打开一个连接。但我似乎找不到用 C++ 做同样事情的方法。我可以连接到数据库,但我不能将它用作一个类,因为我在其中有一个 main() 并且我似乎无法在没有 main 的情况下使其工作。这是我的代码:

// Standard C++ includes
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

// Include the Connector/C++ headers
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"

// Link to the Connector/C++ library
#pragma comment(lib, "mysqlcppconn.lib")

// Specify our connection target and credentials
const string server = "localhost";
const string username = "root";
const string password = "";

int main()
{
sql::Driver *driver; // Create a pointer to a MySQL driver object
sql::Connection *dbConn; // Create a pointer to a database connection object
sql::Statement *stmt; // Create a pointer to a Statement object to hold our SQL commands
sql::ResultSet *res; // Create a pointer to a ResultSet object to hold the results of any queries we run

// Try to get a driver to use to connect to our DBMS
try
{
driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}

// Try to connect to the DBMS server
try
{
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e)
{
cout << "Could not connect to database. Error message: " << e.what() << endl;
system("pause");
exit(1);
}

stmt = dbConn->createStatement();

// Try to query the database
try
{
stmt->execute("USE test");

res = stmt->executeQuery("SELECT * FROM users");

}
catch (sql::SQLException e)
{
cout << "SQL error. Error message: " << e.what() << endl;
system("pause");
exit(1);
}


sql::ResultSetMetaData *res_meta = res -> getMetaData();
int columns = res_meta -> getColumnCount();

while (res->next())
{
for (int i = 1; i <= columns; i++) {
cout << res->getString(i) << " | " ;
}
cout << endl;
}

delete res;
delete stmt;
delete dbConn;
return 0;
}

最佳答案

您需要创建一个(例如class DBConnector)并在头文件中声明函数。例如,这段代码可以进入一个函数:

sql::Driver* DBConnector::GetDriverInstance()
{
try
{
m_driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
return m_driver;
}

这里的sql::Driver *m_driver应该在头文件中声明为类的成员变量。在实际继续编写代码之前,您可能需要阅读更多关于类、成员函数和变量的内容。除此之外,您需要非常注意内存管理。我建议您阅读更多内容并使用智能指针,例如 std::shared_ptr

关于c++ - c++连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48756063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com