头文件 con_mysql.h
- #include <stdlib.h>
- #include <stdio.h>
- #include <mysql/mysql.h>
- #include <syslog.h>
- #include <iostream>
- using namespace std;
- //SQL mysql;
- MYSQL_RES * doQuery(MYSQL &mysql,const char *sql,int type)
- {
- MYSQL_RES *m_res;
- if(mysql_query(&mysql,sql) != 0)
- fprintf(stderr, "mysql_query err: %s",mysql_error(&mysql));
- m_res = mysql_store_result(&mysql);
- if(type==0 && m_res==NULL)
- fprintf(stderr, "get result err: %s",mysql_error(&mysql));
- return m_res;
- }
- bool mysql_con(MYSQL &mysql)
- {
- char *host = "219.223.242.249";
- char *user = "***";
- char *passwd = "***";
- char *db = "***";
- if( mysql_init(&mysql) == NULL )
- return false;
- mysql_options(&mysql,MYSQL_SET_CHARSET_NAME,"gbk");
- if (mysql_real_connect(&mysql,host,user,passwd,db,0,NULL,0) == NULL)
- return false;
- return true;
- }
主程序中
- #include "con_mysql.h"
- void operateDB()
- {
- MYSQL mysql;
- MYSQL_RES *m_res;
- MYSQL_ROW m_row;
- if( mysql_con( mysql ) )
- {
- string sql("");
- sql = "select stock_name,stock_id from hotrank";
- m_res = doQuery( mysql, sql.c_str(), 1 ); //con_mysql.h中定义的方法
- for(int i=0;i<mysql_num_rows(m_res);i++)
- {
- for(int j=0;j<mysql_num_fields(m_res);j++)
- cout<<m_row[j]<<" ";
- cout<<endl;
- }
- mysql_free_result(m_res);
- mysql_close(&mysql);
- }
- else
- cout<<"Connect error!"<<endl;
- }