Hello I've been trying to connect a MySQL database with C++ program but every time I try to connect I get error code 0, could someone help me or tell me what am I doing wrong? Here's my complete code:
#include <iostream>
#include <mysql/mysql.h>
#include <stdio.h>
#define SERVER "localhost"
#define USER "user"
#define PASS "password"
#define DATABASE "database"
int main(){
MYSQL *connect = mysql_init(NULL);
if(!connect){
std::cout<<"MySQL could not connect\n";
return 1;
}
connect = mysql_real_connect(connect, SERVER, USER, PASS, DATABASE, 3306, NULL,0);
if(connect){
std::cout<<"CONNECTION SUCCESS"<<std::endl;
}else{
std::cout<<"CONNECTION FAILED ERROR CODE: "<<mysql_errno(connect)<<std::endl;
}
return 0;
}
(Yes I've already started the server I guess, and created a specific user for the program)
The output I get is:
CONNECTION FAILED ERROR: 0
Try using this code instead (you will need Connector/C++ ):
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
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 <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
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");
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 data 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.