简体   繁体   English

用C ++连接数据库

[英]connecting to database in c++

In php I create a config file that opens a connection to the database and then I use that file in all my other files in order to open a connection also. 在php中,我创建了一个配置文件,该文件打开了与数据库的连接,然后在所有其他文件中使用了该文件,以便也打开了连接。 But I can't seem to find a way to do the same thing with c++. 但是我似乎找不到找到使用c ++做同样事情的方法。 I can connect to the database but I can't use it as a class because I have a main() inside it and I can't seem to make it work without the main. 我可以连接到数据库,但是不能将其用作类,因为我内部有一个main(),而且在没有main的情况下我似乎无法使其正常工作。 This is my code: 这是我的代码:

// 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;
}

You need to create a class (eg class DBConnector )and declare functions in header file. 您需要创建一个class (例如, class DBConnector )并在头文件中声明函数。 For example this piece of code can go into one function: 例如,这段代码可以进入一个函数:

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;
}

Here sql::Driver *m_driver is expected to be declared as a member variable of class in header file. 此处sql::Driver *m_driver预期被声明为头文件中class的成员变量。 You might need to read more about classes and member functions and variables before actually going ahead with code. 在实际进行代码之前,您可能需要阅读有关类,成员函数和变量的更多信息。 Other than this, you need to take very good care of memory management. 除此之外,您需要非常注意内存管理。 I would suggest you read more and use smart pointers like std::shared_ptr . 我建议您阅读更多内容,并使用诸如std::shared_ptr类的智能指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM