想在程序中加入存储数据的功能,程序使用C++语言开发,于是就打算看看C++如何访问MySql,之前自学过MySql,也安装过MySql的开发包,相应的头文件已经有了,看了一下mysql.h头文件,里面有C的API,所以就需要用C++来封装一下,借鉴一下网上已有的资源,下面列出封装后的程序:
MySqlDb.h
#ifndef MYSQLDB_H
#define MYSQLDB_H
#include <mysql/mysql.h>
#include <string>
using namespace std;
class MySqlDb
{
public:
MySqlDb();
bool initDB(string server_host , string user, string password, string db_name);
bool executeSQL(string sql_str);
bool create_table(string table_str_sql);
~MySqlDb();
private:
MYSQL *connection;
MYSQL_RES *res;
MYSQL_ROW row;
};
#endif
MySqlDb.cpp
#include "MySqlDb.h"
#include <stdlib.h>
#include <iostream>
MySqlDb::MySqlDb()
{
//init mysql connection
connection = mysql_init(NULL);
if(connection == NULL)
{
cout《"mysql_init error\n";
exit(1);
}
}
MySqlDb::~MySqlDb()
{
//shutdown connect
if(connection != NULL)
{
mysql_close(connection);
}
}
//
bool MySqlDb::initDB(string server_host , string user, string password , string db_name )
{
//implement connect to mysql
connection = mysql_real_connect(connection , server_host.c_str() ,
user.c_str() , password.c_str() , db_name.c_str() , 0 , NULL , 0);
if(connection == NULL)
{
cout《"mysql_real_connect error\n";
exit(1);
}
return true;
}
//execute mysql
bool MySqlDb::executeSQL(string sql_str)
{
// query
if(mysql_query(connection, "set names utf8"))
{
cout《mysql_errno(connection)《" "《mysql_error(connection)《"\n";
}
int t = mysql_query(connection, sql_str.c_str());
if(t)
{
cout《"Error making query: "《mysql_error(connection)《"\n";
exit(1);
}
else
{
res = mysql_use_result(connection);
if(res)
{
for(int i = 0 ; i < mysql_field_count(connection) ; i++)
{
row = mysql_fetch_row(res);
if(row <= 0)
{
break;
}
for(int r = 0 ; r < mysql_num_fields(res) ; r ++)
{
cout《row[r]《" ";
}
cout《"\n";
}
}
mysql_free_result(res);
}
return true;
}
//create table
bool MySqlDb::create_table(string table_str_sql)
{
int t = mysql_query(connection , table_str_sql.c_str());
if(t)
{
cout《"Error making query: "《mysql_error(connection)《"\n";
exit(1);
}
return true;
}