How to connect MySQL in C++
文章目录
Introduction
Today I want to share a way connect MySQL database in C++. Not using connector api, but using mysql library. It is difficult but interesting. I think it can help us learn the implement of MySQL better. Action!
Prepare work
Before coding , we should do some prepare work . The detail of the work is :
find the libary
step.1
find the lib at your PC or Server. Example: my installed storage path is D:/MYSQL/mysql-5.7.23-winx64 , so go to /lib in the storage path. And then you should search the libmysql.dll & libmysql.lib.
step.2
add link in vs.like this:
next part like this:
step.3
import the mysql.h which located in /include in storage path. operation like this:
step.4
cp the libmysql.dll to the debug code path, maybe it is /Debug or /X64/Debug in your pc.
OK ! work done!
Coding
Please follow me to code now .Or you can copy my code to compile and run.
#include<iostream>
#include "stdio.h"
#include "mysql.h"
#include<time.h>
#include<websocket.h>
using namespace std;
int main()
{
const char user[] = "root";
const char pswd[] = "psw";
const char host[] = "ip_address";
const char db[] = "db_name";
unsigned int port = 3306;//port
MYSQL sql_conn;
MYSQL_RES* result = nullptr;
MYSQL_ROW sql_row;
int res;
mysql_init(&sql_conn);
if (mysql_real_connect(&sql_conn, host, user, pswd, db, port, nullptr, 0))
{
mysql_query(&sql_conn, "SET NAMES GBK");
res = mysql_query(&sql_conn, "select * from admin");
if (!res)
{
result = mysql_store_result(&sql_conn);
if (result != nullptr)
{
while (sql_row = mysql_fetch_row(result))
{
//username and password is the col names
cout << "username:" << sql_row[0] << endl;
cout << "password:" << sql_row[1] << endl;
}
}
}
else
{
cout << "query sql failed!" << endl;
}
}
else
{
cout << "connect failed!" << endl;
}
if (result != nullptr)
mysql_free_result(result);
mysql_close(&sql_conn);
//test
return 0;
}