C++访问MYSQL数据库

时间:2022-02-17 09:14:01
#include <Windows.h>
#include <mysql.h>
#include <string>
#include <iostream>
#include<iomanip>

// SDK software development kit
//简易版本的服务器
using namespace std;
//#pragma comment(lib,"D:\\Program Files\\MySQL\\MySQL Server 5.6\\lib\\libmysql.lib")
int main()
{
const char user[] = "root";
const char pswd[] = "12345678";
const char host[] = "localhost";
const char mysql[] = "myfirstsql";
unsigned int port = 3306;
MYSQL myCont;//句柄 数据库变量
MYSQL_RES *result;
MYSQL_ROW sql_row;
int res;
mysql_init(&myCont);
if (mysql_real_connect(&myCont, host, user, pswd, mysql, port, NULL, 0))
{
mysql_query(&myCont, "SET NAMES GBK"); //设置编码格式
res = mysql_query(&myCont, "select * from mytable");//查询、执行命令 返回0为成功
// res = mysql_query(&myCont, "insert into mytable(id,name,sex) values(NULL,'hang','男')");//插入
//res = mysql_query(&myCont, "delete from students where name = Li'");//删除
//res = mysql_query(&myCont, "update students set tel = '1423636' where name = 'He'");//更新
if (!res)
{
result = mysql_store_result(&myCont);
if (result)
{
cout <<left<<setw(3)<< "id"<<setw(8) << "name" << setw(2)<<"sex" << endl;
while (sql_row = mysql_fetch_row(result))//获取具体的数据
{
cout << left <<setw(2)<<sql_row[0] << " ";
cout << left <<setw(8) << sql_row[1] << " ";
cout << left <<setw(2) << sql_row[2] << " ";
}
}
}
else
{
cout << "query sql failed!" << endl;
}
}
else
{
cout << "connect failed!" << endl;
}
if (result != NULL)
mysql_free_result(result);
mysql_close(&myCont);
system("pause");
return 0;

}