#include<iostream>
#include<string>
#include<mysql/mysql.h>
如果机器上装的库都是在标准搜索目录,那么就可以直接用:
g++ $(mysql_config --cflags) xxx.cpp -o xxx $(mysql_config --libs)
如果编译出错,提示说找不到头文件或者函数定义之类的,就说明库不在标准目录下。
此时可以到根目录下用:
find . -name "mysql.h"和find . -name "mysqlclient"
查看一下本机的mysql目录(假设为/usr/local/mysql-5.0.67/include/和/usr/local/mysql-5.0.67/lib/mysql),
然后用:
g++ -I/usr/local/mysql-5.0.67/include/ xxx.cpp -L/usr/local/mysql-5.0.67/lib/mysql -lmysqlclient
便可生成a.out
#include<iostream>
#include <stdlib.h>
#include<string>
#include<vector>
#include<mysql/mysql.h>
using namespace std;
int main()
{
MYSQL *conn;
MYSQL_RES *result;
MYSQL_ROW row;
int isp[24] = {0};
conn = mysql_init(NULL); // 初始化数据库连接变量
if(conn == NULL)
{
cout << "Error:" << mysql_error(conn);
return 0;
}
// 函数mysql_real_connect建立一个数据库连接
// 成功返回MYSQL*连接句柄,失败返回NULL
conn = mysql_real_connect(conn, "IP地址", "用户名", "密码", "数据库", 0, NULL, CLIENT_MULTI_STATEMENTS);
if(conn == NULL)
{
cout << "Error:" << mysql_error(conn);
return 0;
}
string sql = "select ip, min(wAverDelay) from hummer_ip_speed_addip_20151102_Hash55 group by ip";
if(mysql_query(conn, sql.c_str()))
{
cout << "Query Error 1:" << mysql_error(conn);
return 0;
}
result = mysql_use_result(conn); // 获取结果集
vector<vector<string> > vec;
int i = 0;
while ((row = mysql_fetch_row(result)) != NULL)
{
vector<string> tmp;
tmp.push_back(row[0]);
tmp.push_back(row[1]);
vec.push_back(tmp);
}
mysql_free_result(result); //释放了 才能进行下一次query
for (int i = 0; i < vec.size(); ++i)
{
sql = "select isp3+0 from hummer_ip_speed_addip_20151102_Hash55 where ip=" + vec[i][0] + " and wAverDelay=" + vec[i][1];
if(mysql_query(conn, sql.c_str()))
{
cout << "Query Error 2:" << mysql_error(conn);
return 0;
}
result = mysql_use_result(conn); // 获取结果集
if ((row = mysql_fetch_row(result)) != NULL)
{
++isp[atoi(row[0])];
}
// 释放结果集的内存
mysql_free_result(result);
}
for (int i = 1; i < 24; ++i)
{
cout << i << ": " << isp[i] << endl;
}
return 0;
}