c++连接MySql数据库

时间:2021-11-26 11:27:37
#include <iostream>
#include<mysql/mysql.h>

using namespace std;

MYSQL *con;//该结构体代表了一个数据库连接句柄
MYSQL_RES *res;//该结构体代表返回行的查询结果,返回的信息作为结果集,时一张数据表
MYSQL_ROW row;//这个是一行数据的显示
int main() {

char server[20] = "localhost";
char user[20] = "root";
char password[20] = "123456";
char database[20] = "mystudent";

con = mysql_init(NULL);//成功con不为NULL,失败con为NULL
if (!mysql_real_connect(con, server, user, password, database, 0, NULL, 0)) {
cout << "connect failed" << endl;
}
mysql_set_character_set(con, "utf8");

if (mysql_query(con, "select * from student")) {
cout << "query failed";
}//成功返回0,不成功返回非0

res = mysql_use_result(con);
//依次从结果集中获取每一行并打印
while ((row = mysql_fetch_row(res)) != NULL) {
cout << row[0] << " " << row[1] << " " << row[2] << " " << endl;
}
//释放结果集
mysql_free_result(res);
//关闭数据库
mysql_close(con);

return 0;
}