Cómo conectar la base de datos mySQL usando C++

Cómo conectar la base de datos mySQL usando C++


Estoy tratando de conectar la base de datos desde mi sitio web y mostrar algunas filas usando C++.
Básicamente, estoy tratando de crear una aplicación que realice una consulta de selección de una tabla de la base de datos de mi sitio. Ahora, esto debe ser posible porque he visto toneladas de aplicaciones haciéndolo.


¿Cómo hago esto? ¿Puede alguien hacer un ejemplo y decirme qué bibliotecas debo usar?


Respuestas:


Encontrado aquí:


/* 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"); // 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;
}

Algunas respuestas de código


wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm rpm -ivh mysql-community-release-el7-5.noarch.rpm yum update yum install mysql-server 
systemctl start mysqld
systemctl status mysqld
mysql -u root -p
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE my_table (table_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, first_name TEXT, last_name TEXT);
INSERT INTO my_table(first_name, last_name) VALUES('Cristiano', 'Ronaldo');
INSERT INTO my_table(first_name, last_name) values('Lionel', 'Messi');
SELECT * FROM my_table;
yum info mysql-devel
yum install mysql-devel
#include <mysql.h>
#include <stdio.h>
int main() { MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "";
/*password is not set in this example*/ char *database = "mydb";
conn = mysql_init(NULL);
/* Connect to database */ if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { printf("Failed to connect MySQL Server %s. Error: %s\n", server, mysql_error(conn));
return 0;
} /* Execute SQL query to fetch all table names.*/ if (mysql_query(conn, "show tables")) { printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
return 0;
} res = mysql_use_result(conn);
/* Output table name */ printf("MySQL Tables in mydb database:\n");
while ((row = mysql_fetch_row(res)) != NULL) printf("%s \n", row[0]);
/* free results */ mysql_free_result(res);
/* send SQL query */ if (mysql_query(conn, "select * from my_table")) { printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
return 0;
} res = mysql_store_result(conn);
if (res == NULL) { return 0;
} int columns = mysql_num_fields(res);
int i = 0;
printf("Entries in the table my_table:\n");
while(row = mysql_fetch_row(res)) { for (i = 0;
i <
columns;
i++) {
printf("%s ", row[i] ? row[i] : "NULL");
} printf("\n");
} mysql_free_result(res);
mysql_close(conn);
return 1;
}
 conn = mysql_init(NULL);
/* Connect to database */ if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { printf("Failed to connect MySQL Server %s. Error: %s\n", server, mysql_error(conn));
return 0;
}
/* Execute SQL query to fetch all table names.*/  if (mysql_query(conn, "show tables"))  {    printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
return 0;
} res = mysql_use_result(conn);
/* Output table name */ printf("MySQL Tables in mydb database:\n");
while ((row = mysql_fetch_row(res)) != NULL) printf("%s \n", row[0]);
/* free results */ mysql_free_result(res);
if (mysql_query(conn, "select * from my_table"))  {    printf("Failed to execute quesry. Error: %s\n", mysql_error(conn));
return 0;
} res = mysql_store_result(conn);
if (res == NULL) { return 0;
}
int columns = mysql_num_fields(res);
int i = 0;
printf("Entries in the table my_table:\n");
while(row = mysql_fetch_row(res)) { for (i = 0;
i <
columns;
i++) {
printf("%s ", row[i] ? row[i] : "NULL");
} printf("\n");
}
gcc -o mysqlc $(mysql_config --cflags) $(mysql_config --libs) prueba.c
./mysqlc MySQL Tables in mysql database: my_table 1 Cristiano Ronaldo 2 Lionel Messi 

No