C++实现PyMysql的基本功能实例详解

所属分类: 软件编程 / C 语言 阅读数: 111
收藏 0 赞 0 分享

用C++实现一个Thmysql类,实现Python标准库PyMysql的基本功能,并提供与PyMysql类似的API,并用pybind11将Thmysql封装为Python库。

PyMysql Thmysql(C++) Thmysql(Python)
connect connect connect
cursor —— ——
execute execute execute
fetchone fetchone fetchone
fetchall fetchall fetchall
close close close

一.开发环境

  • Windows64位操作系统;
  • mysql 5.5.28 for Win64(x86);
  • pycharm 2019.1.1。

二.PyMysql数据库查询

#文件名:python_test.py
import pymysql
# 连接database
conn = pymysql.connect(host="localhost",user="root",password="123456",
      database="test",charset="utf8")

# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
# 执行SQL语句
cursor.execute("use information_schema")

cursor.execute("select version();")
first_line = cursor.fetchone()
print(first_line)

cursor.execute("select * from character_sets;")
res = cursor.fetchall()
print(res)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()

三.开发步骤

  1. 将mysql安装目录下的include和lib文件夹拷到project目录中;
  2. 将lib文件夹中的libmysql.dll文件拷到system32路径下;
  3. 定义MysqlInfo结构体,实现C++版的Thmysql类;
  4. 编写封装函数;
  5. 通过setuptools将C++代码编译为Python库。

四.代码实现

// 文件名:thmysql.h
#include <Windows.h>
#include "mysql.h"
#include <iostream>
#include <string>
#include <vector>

#pragma comment(lib, "lib/libmysql.lib")
using namespace std;

typedef struct MysqlInfo{
 string m_host;
 string m_user;
 string m_passwd;
 string m_db;
 unsigned int m_port;
 string m_unix_socket;
 unsigned long m_client_flag;

 MysqlInfo(){}
 MysqlInfo(string host, string user, string passwd, string db, unsigned int port,
     string unix_socket, unsigned long client_flag){
  m_host = host;
  m_user = user;
  m_passwd = passwd;
  m_db = db;
  m_port = port;
  m_unix_socket = unix_socket;
  m_client_flag = client_flag;
 }
}MysqlInfo;

class Thmysql{
 public:
  Thmysql();
  void connect(MysqlInfo&);
  void execute(string);
  vector<vector<string>> fetchall();
  vector<string> fetchone();
  void close();
 private:
  MYSQL mysql;
  MYSQL_RES * mysql_res;
  MYSQL_FIELD * mysql_field;
  MYSQL_ROW mysql_row;
  int columns;
  vector<vector<string>> mysql_data;
  vector<string> first_line;
};
// 文件名:thmysql.cpp
#include <iostream>
#include "thmysql.h"

Thmysql::Thmysql(){
 if(mysql_library_init(0, NULL, NULL) != 0){
  cout << "MySQL library initialization failed" << endl;
 }
 if(mysql_init(&mysql) == NULL){
  cout << "Connection handle initialization failed" << endl;
 }
}

void Thmysql::connect(MysqlInfo& msInfo){
 string host = msInfo.m_host;
 string user = msInfo.m_user;
 string passwd = msInfo.m_passwd;
 string db = msInfo.m_db;
 unsigned int port = msInfo.m_port;
 string unix_socket = msInfo.m_unix_socket;
 unsigned long client_flag = msInfo.m_client_flag;

 if(mysql_real_connect(&mysql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(),
  port, unix_socket.c_str(), client_flag) == NULL){
  cout << "Unable to connect to MySQL" << endl;
 }
}

void Thmysql::execute(string sqlcmd){
 mysql_query(&mysql, sqlcmd.c_str());

 if(mysql_errno(&mysql) != 0){
  cout << "error: " << mysql_error(&mysql) << endl;
 }
}

vector<vector<string>> Thmysql::fetchall(){
 // 获取 sql 指令的执行结果
 mysql_res = mysql_use_result(&mysql);
 // 获取查询到的结果的列数
 columns = mysql_num_fields(mysql_res);
 // 获取所有的列名
 mysql_field = mysql_fetch_fields(mysql_res);
 mysql_data.clear();
 while(mysql_row = mysql_fetch_row(mysql_res)){
  vector<string> row_data;
  for(int i = 0; i < columns; i++){
   if(mysql_row[i] == nullptr){
    row_data.push_back("None");
   }else{
    row_data.push_back(mysql_row[i]);
   }
  }
  mysql_data.push_back(row_data);
 }
 // 没有mysql_free_result会造成内存泄漏:Commands out of sync; you can't run this command now
 mysql_free_result(mysql_res);
 return mysql_data;
}

vector<string> Thmysql::fetchone(){
 // 获取 sql 指令的执行结果
 mysql_res = mysql_use_result(&mysql);
 // 获取查询到的结果的列数
 columns = mysql_num_fields(mysql_res);
 // 获取所有的列名
 mysql_field = mysql_fetch_fields(mysql_res);
 first_line.clear();
 mysql_row = mysql_fetch_row(mysql_res);
 for(int i = 0; i < columns; i++){
  if(mysql_row[i] == nullptr){
   first_line.push_back("None");
  }else{
   first_line.push_back(mysql_row[i]);
  }
 }
 mysql_free_result(mysql_res);
 return first_line;
}

void Thmysql::close(){
 mysql_close(&mysql);
 mysql_library_end();
}
// 文件名:thmysql_wrapper.cpp
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "thmysql.h"

namespace py = pybind11;

PYBIND11_MODULE(thmysql, m){
 m.doc() = "C++操作Mysql";
 py::class_<MysqlInfo>(m, "MysqlInfo")
  .def(py::init())
  .def(py::init<string, string, string, string, unsigned int, string, unsigned long>(),
    py::arg("host"), py::arg("user"), py::arg("passwd"), py::arg("db"),py::arg("port"),
    py::arg("unix_socket") = "NULL", py::arg("client_flag")=0)
  .def_readwrite("host", &MysqlInfo::m_host)
  .def_readwrite("user", &MysqlInfo::m_user)
  .def_readwrite("passwd", &MysqlInfo::m_passwd)
  .def_readwrite("db", &MysqlInfo::m_db)
  .def_readwrite("port", &MysqlInfo::m_port)
  .def_readwrite("unix_socket", &MysqlInfo::m_unix_socket)
  .def_readwrite("client_flag", &MysqlInfo::m_client_flag);

 py::class_<Thmysql>(m, "Thmysql")
  .def(py::init())
  .def("connect", &Thmysql::connect)
  .def("execute", &Thmysql::execute, py::arg("sql_cmd"))
  .def("fetchall", &Thmysql::fetchall)
  .def("fetchone", &Thmysql::fetchone)
  .def("close", &Thmysql::close);
}
#文件名:setup.py
from setuptools import setup, Extension

functions_module = Extension(
 name='thmysql',
 sources=['thmysql.cpp', 'thmysql_wrapper.cpp'],
 include_dirs=[r'D:\software\pybind11-master\include',
     r'D:\software\Anaconda\include',
     r'D:\project\thmysql\include'],
)

setup(ext_modules=[functions_module])

五.Thmysql数据库查询

#文件名:test.py
from thmysql import Thmysql, MysqlInfo

info = MysqlInfo("localhost", "root", "123456", "", 3306)
conn = Thmysql()
# 连接database
conn.connect(info)
# 执行SQL语句
conn.execute("use information_schema")

conn.execute("select version();")
first_line = conn.fetchone()
print(first_line)

conn.execute("select * from character_sets;")
res = conn.fetchall()
print(res)
# 关闭数据库连接
conn.close()

 

更多精彩内容其他人还在看

用标准c++实现string与各种类型之间的转换

这个类在头文件中定义, < sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本
收藏 0 赞 0 分享

C++如何通过ostringstream实现任意类型转string

再使用整型转string的时候感觉有点棘手,因为itoa不是标准C里面的,而且即便是有itoa,其他类型转string不是很方便。后来去网上找了一下,发现有一个好方法
收藏 0 赞 0 分享

C/C++指针小结

要搞清一个指针需要搞清指针的四方面的内容:指针的类型,指针所指向的类型,指针的值或者叫指针所指向的内存区,还有指针本身所占据的内存区
收藏 0 赞 0 分享

C++ 类的静态成员深入解析

在C++中类的静态成员变量和静态成员函数是个容易出错的地方,本文先通过几个例子来总结静态成员变量和成员函数使用规则,再给出一个实例来加深印象
收藏 0 赞 0 分享

C++类的静态成员初始化详细讲解

通常静态数据成员在类声明中声明,在包含类方法的文件中初始化.初始化时使用作用域操作符来指出静态成员所属的类.但如果静态成员是整型或是枚举型const,则可以在类声明中初始化
收藏 0 赞 0 分享

C++类静态成员与类静态成员函数详解

静态成员不可在类体内进行赋值,因为它是被所有该类的对象所共享的。你在一个对象里给它赋值,其他对象里的该成员也会发生变化。为了避免混乱,所以不可在类体内进行赋值
收藏 0 赞 0 分享

C++中的friend友元函数详细解析

友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类。友元函数的特点是能够访问类中的私有成员的非成员函数。友元函数从语法上看,它与普通函数一样,即在定义上和调用上与普通函数一样
收藏 0 赞 0 分享

static全局变量与普通的全局变量的区别详细解析

以下是对static全局变量与普通的全局变量的区别进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所帮助
收藏 0 赞 0 分享

C++ explicit关键字的应用方法详细讲解

C++ explicit关键字用来修饰类的构造函数,表明该构造函数是显式的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢?下面就让我们一起来看看这方面的知识吧
收藏 0 赞 0 分享

教你5分钟轻松搞定内存字节对齐

随便google一下,人家就可以跟你解释的,一大堆的道理,我们没怎么多时间,讨论为何要对齐.直入主题,怎么判断内存对齐规则,sizeof的结果怎么来的,请牢记以下3条原则
收藏 0 赞 0 分享
查看更多