How to connect MySQL in C++

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:

[外链图片转存失败(img-gz8J0Sbj-1565704555002)(C:\Users\SAMSUNG\Desktop\暑假\WeChat 圖片_20190813214536.png)]

step.3

​ import the mysql.h which located in /include in storage path. operation like this:

[外链图片转存失败(img-xayTw8DV-1565704555002)(C:\Users\SAMSUNG\Desktop\暑假\WeChat 圖片_20190813214849.png)]

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


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值