cpp
#include "mysql.h"
MYSQL *mysql;
MYSQL_RES *rec;
MYSQL_ROW row;
(1)连接
cpp
char *server = "localhost";
char *user = "root";
char *password = "hello";
char *database = "mysql";
mysql = mysql_init(NULL);
if(!mysql_real_connect(mysql, server, user, password, database, 0, NULL, 0))
printf("Connect Failed: %sn\n", mysql_error(mysql));
else
printf("Connect Succeed ! \n");
(2)运行
cpp
string str="show databases;";
if(mysql_real_query(mysql,str.c_str(),str.length()))
{
cout << mysql_error(mysql) << endl;
return -1;
}
(3)显示结果
cpp
rec=mysql_store_result(mysql);
while(row = mysql_fetch_row(rec))
{
for(int i = 0;i < mysql_num_fields(rec);i++)
{
if(row[i] != NULL)
cout << row[i] << "\t";
else
cout << "<null>" << "\t";
}
cout << "\n";
}
(4)释放记录
cpp
mysql_free_result(rec);
(5)关闭连接
cpp
mysql_close(mysql);
(6)获取记录数
cpp
mysql_num_fields(rec);