How to connect mySQL database using C++

前端 未结 4 1110
执笔经年
执笔经年 2020-11-30 21:55

I\'m trying to connect the database from my website and display some rows using C++. So bascily I\'m trying to make an application that does a select query from a table from

4条回答
  •  难免孤独
    2020-11-30 22:23

    Found here:

    /* Standard C++ includes */
    #include 
    #include 
    
    /*
      Include directly the different
      headers from cppconn/ and mysql_driver.h + mysql_util.h
      (and mysql_connection.h). This will reduce your build time!
    */
    #include "mysql_connection.h"
    
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main(void)
    {
    cout << endl;
    cout << "Running 'SELECT 'Hello World!' »
       AS _message'..." << endl;
    
    try {
      sql::Driver *driver;
      sql::Connection *con;
      sql::Statement *stmt;
      sql::ResultSet *res;
    
      /* Create a connection */
      driver = get_driver_instance();
      con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
      /* Connect to the MySQL test database */
      con->setSchema("test");
    
      stmt = con->createStatement();
      res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
      while (res->next()) {
        cout << "\t... MySQL replies: ";
        /* Access column data by alias or column name */
        cout << res->getString("_message") << endl;
        cout << "\t... MySQL says it again: ";
        /* Access column fata by numeric offset, 1 is the first column */
        cout << res->getString(1) << endl;
      }
      delete res;
      delete stmt;
      delete con;
    
    } catch (sql::SQLException &e) {
      cout << "# ERR: SQLException in " << __FILE__;
      cout << "(" << __FUNCTION__ << ") on line " »
         << __LINE__ << endl;
      cout << "# ERR: " << e.what();
      cout << " (MySQL error code: " << e.getErrorCode();
      cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }
    
    cout << endl;
    
    return EXIT_SUCCESS;
    }
    

提交回复
热议问题