当前位置:首页 > 通信资讯 > 正文

pymysql操作(pymysql菜鸟教程)

用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数据库查询

  1. #文件名:python_test.py
  2. import pymysql
  3. # 连接database
  4. conn = pymysql.connect(host="localhost",user="root",password="123456",
  5. database="test",charset="utf8")
  6. # 得到一个可以执行SQL语句的光标对象
  7. cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
  8. # 执行SQL语句
  9. cursor.execute("use information_schema")
  10. cursor.execute("select version();")
  11. first_line = cursor.fetchone()
  12. print(first_line)
  13. cursor.execute("select * from character_sets;")
  14. res = cursor.fetchall()
  15. print(res)
  16. # 关闭光标对象
  17. cursor.close()
  18. # 关闭数据库连接
  19. conn.close()

pymysql操作(pymysql菜鸟教程)

三.开发步骤

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

四.代码实现

  1. // 文件名:thmysql.h
  2. #include <Windows.h>
  3. #include "mysql.h"
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #pragma comment(lib, "lib/libmysql.lib")
  8. using namespace std;
  9. typedef struct MysqlInfo{
  10. string m_host;
  11. string m_user;
  12. string m_passwd;
  13. string m_db;
  14. unsigned int m_port;
  15. string m_unix_socket;
  16. unsigned long m_client_flag;
  17. MysqlInfo(){}
  18. MysqlInfo(string host, string user, string passwd, string db, unsigned int port,
  19. string unix_socket, unsigned long client_flag){
  20. m_host = host;
  21. m_user = user;
  22. m_passwd = passwd;
  23. m_db = db;
  24. m_port = port;
  25. m_unix_socket = unix_socket;
  26. m_client_flag = client_flag;
  27. }
  28. }MysqlInfo;
  29. class Thmysql{
  30. public:
  31. Thmysql();
  32. void connect(MysqlInfo&);
  33. void execute(string);
  34. vector<vector<string>> fetchall();
  35. vector<string> fetchone();
  36. void close();
  37. private:
  38. MYSQL mysql;
  39. MYSQL_RES * mysql_res;
  40. MYSQL_FIELD * mysql_field;
  41. MYSQL_ROW mysql_row;
  42. int columns;
  43. vector<vector<string>> mysql_data;
  44. vector<string> first_line;
  45. };
  46. // 文件名:thmysql.cpp
  47. #include <iostream>
  48. #include "thmysql.h"
  49. Thmysql::Thmysql(){
  50. if(mysql_library_init(0, NULL, NULL) != 0){
  51. cout << "MySQL library initialization failed" << endl;
  52. }
  53. if(mysql_init(&mysql) == NULL){
  54. cout << "Connection handle initialization failed" << endl;
  55. }
  56. }
  57. void Thmysql::connect(MysqlInfo& msInfo){
  58. string host = msInfo.m_host;
  59. string user = msInfo.m_user;
  60. string passwd = msInfo.m_passwd;
  61. string db = msInfo.m_db;
  62. unsigned int port = msInfo.m_port;
  63. string unix_socket = msInfo.m_unix_socket;
  64. unsigned long client_flag = msInfo.m_client_flag;
  65. if(mysql_real_connect(&mysql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(),
  66. port, unix_socket.c_str(), client_flag) == NULL){
  67. cout << "Unable to connect to MySQL" << endl;
  68. }
  69. }
  70. void Thmysql::execute(string sqlcmd){
  71. mysql_query(&mysql, sqlcmd.c_str());
  72. if(mysql_errno(&mysql) != 0){
  73. cout << "error: " << mysql_error(&mysql) << endl;
  74. }
  75. }
  76. vector<vector<string>> Thmysql::fetchall(){
  77. // 获取 sql 指令的执行结果
  78. mysql_res = mysql_use_result(&mysql);
  79. // 获取查询到的结果的列数
  80. columns = mysql_num_fields(mysql_res);
  81. // 获取所有的列名
  82. mysql_field = mysql_fetch_fields(mysql_res);
  83. mysql_data.clear();
  84. while(mysql_row = mysql_fetch_row(mysql_res)){
  85. vector<string> row_data;
  86. for(int i = 0; i < columns; i++){
  87. if(mysql_row[i] == nullptr){
  88. row_data.push_back("None");
  89. }else{
  90. row_data.push_back(mysql_row[i]);
  91. }
  92. }
  93. mysql_data.push_back(row_data);
  94. }
  95. // 没有mysql_free_result会造成内存泄漏:Commands out of sync; you can't run this command now
  96. mysql_free_result(mysql_res);
  97. return mysql_data;
  98. }
  99. vector<string> Thmysql::fetchone(){
  100. // 获取 sql 指令的执行结果
  101. mysql_res = mysql_use_result(&mysql);
  102. // 获取查询到的结果的列数
  103. columns = mysql_num_fields(mysql_res);
  104. // 获取所有的列名
  105. mysql_field = mysql_fetch_fields(mysql_res);
  106. first_line.clear();
  107. mysql_row = mysql_fetch_row(mysql_res);
  108. for(int i = 0; i < columns; i++){
  109. if(mysql_row[i] == nullptr){
  110. first_line.push_back("None");
  111. }else{
  112. first_line.push_back(mysql_row[i]);
  113. }
  114. }
  115. mysql_free_result(mysql_res);
  116. return first_line;
  117. }
  118. void Thmysql::close(){
  119. mysql_close(&mysql);
  120. mysql_library_end();
  121. }
  1. // 文件名:thmysql_wrapper.cpp
  2. #include "pybind11/pybind11.h"
  3. #include "pybind11/stl.h"
  4. #include "thmysql.h"
  5. namespace py = pybind11;
  6. PYBIND11_MODULE(thmysql, m){
  7. m.doc() = "C++操作Mysql";
  8. py::class_<MysqlInfo>(m, "MysqlInfo")
  9. .def(py::init())
  10. .def(py::init<string, string, string, string, unsigned int, string, unsigned long>(),
  11. py::arg("host"), py::arg("user"), py::arg("passwd"), py::arg("db"),py::arg("port"),
  12. py::arg("unix_socket") = "NULL", py::arg("client_flag")=0)
  13. .def_readwrite("host", &MysqlInfo::m_host)
  14. .def_readwrite("user", &MysqlInfo::m_user)
  15. .def_readwrite("passwd", &MysqlInfo::m_passwd)
  16. .def_readwrite("db", &MysqlInfo::m_db)
  17. .def_readwrite("port", &MysqlInfo::m_port)
  18. .def_readwrite("unix_socket", &MysqlInfo::m_unix_socket)
  19. .def_readwrite("client_flag", &MysqlInfo::m_client_flag);
  20. py::class_<Thmysql>(m, "Thmysql")
  21. .def(py::init())
  22. .def("connect", &Thmysql::connect)
  23. .def("execute", &Thmysql::execute, py::arg("sql_cmd"))
  24. .def("fetchall", &Thmysql::fetchall)
  25. .def("fetchone", &Thmysql::fetchone)
  26. .def("close", &Thmysql::close);
  27. }
  28. #文件名:setup.py
  29. from setuptools import setup, Extension
  30. functions_module = Extension(
  31. name='thmysql',
  32. sources=['thmysql.cpp', 'thmysql_wrapper.cpp'],
  33. include_dirs=[r'D:\software\pybind11-master\include',
  34. r'D:\software\Anaconda\include',
  35. r'D:\project\thmysql\include'],
  36. )
  37. setup(ext_modules=[functions_module])

五.Thmysql数据库查询

  1. #文件名:test.py
  2. from thmysql import Thmysql, MysqlInfo
  3. info = MysqlInfo("localhost", "root", "123456", "", 3306)
  4. conn = Thmysql()
  5. # 连接database
  6. conn.connect(info)
  7. # 执行SQL语句
  8. conn.execute("use information_schema")
  9. conn.execute("select version();")
  10. first_line = conn.fetchone()
  11. print(first_line)
  12. conn.execute("select * from character_sets;")
  13. res = conn.fetchall()
  14. print(res)
  15. # 关闭数据库连接
  16. conn.close()

pymysql操作(pymysql菜鸟教程)

总结

到此这篇关于C++实现PyMysql的基本功能的文章就介绍到这了,更多相关c++ pymysql内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://segmentfault.com/a/1190000021875615

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。