c++通过mariadb connector连接mysql8.0

#include
#include

int main(int argc, char* argv[]) {
	MYSQL* con = mysql_init(nullptr);
	MYSQL_RES* res;
	MYSQL_ROW row;
	MYSQL_FIELD* fields;
	int column_count;
	int i;
	if (!con)
	{
		std::cout << "failed to init mysql connection" << mysql_error(con) << std::endl;
		exit(1);
	}

	if (!mysql_real_connect(con, "localhost", "root", nullptr, nullptr, 0, nullptr, 0))
	{
		std::cout << "failed to connect to mysql " << mysql_error(con) << std::endl;
		mysql_close(con);
		exit(1);
	}

	if (mysql_query(con, "select * from mysql.user"))
	{
		std::cout << "failed to execute sql " << mysql_error(con) << std::endl;
		mysql_close(con);
		exit(1);
	}
	else
	{
		std::cout << "query success" << mysql_error(con) << std::endl;
	}
	if (!(res = mysql_store_result(con)))
	{
		std::cout << "failed to get the result of sql " << mysql_error(con) << std::endl;
	}

	column_count = mysql_num_fields(res);
	std::cout << "affected " << mysql_affected_rows(con) <<" rows"<< std::endl;
	std::cout << mysql_num_rows(res) << " rows in set" << std::endl;
	std::cout << column_count << " columns in set" << std::endl;
	fields = mysql_fetch_fields(res);

	for (i = 0; i < column_count; ++i)
	{
		std::cout << fields[i].name<<"\t";
	}
	std::cout << std::endl;
	while ((row = mysql_fetch_row(res)))
	{
		for (i = 0; i < column_count; ++i)
		{
			if (!row[i])
			{
				std::cout << "NULL\t";
				continue;
			}
			std::cout << row[i] << "\t";
		}
		std::cout << std::endl;
	}
	mysql_free_result(res);
	mysql_close(con);
	mysql_library_end();
	return 0;
}

你可能感兴趣的:(mysql)