linux 下C++连接mysql数据库
来源:互联网 发布:福建话翻译软件 编辑:程序博客网 时间:2024/06/02 15:00
想在程序中加入存储数据的功能,程序使用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;
}
- linux下c语言连接mysql数据库
- Linux下C连接MySQL数据库方法
- Linux下C连接MySQL数据库
- Linux 下 C语言连接MYSQL数据库
- Linux下C连接MySQL数据库方法
- Linux下用C语言API连接MySQL数据库
- Linux下用C语言API连接MySQL数据库
- Linux下C语言API连接MySQL数据库编译选项
- Linux 下 C 语言连接 MySQL 数据库 / 西安嵌入式培训
- Linux下用C语言API连接MySQL数据库
- linux ubuntu下C语言与数据库mysql连接
- Linux下用C语言连接MySQL数据库
- Linux 环境下使用 C API 连接 MYSQL 数据库
- Linux centos 7下: 用 C 语言连接 MySQL数据库
- Linux C连接Mysql数据库
- Linux C连接Mysql数据库
- Linux C连接Mysql数据库
- linux c 连接mysql数据库
- 注册表
- SVN-subversion
- 理解autorelease
- jsp 伪静态
- hibernate自动更新时方言问题
- linux 下C++连接mysql数据库
- Visual Studio调试技巧
- 吉他
- [Java,Processing]关于Application的Applet的弹窗问题
- 从ADS到RealViewMDK —— ARM-MCU新一代集成开发环境
- 无法检索“mvc4.Models.Movie”的元数据的解决方案。
- uva 1427 - Parade(dp+单调队列)
- request.getParameter()和request.getAttribute()的区别
- 传统应用开发公司如何升级自己的平台