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

2020-03-01 14:00:47王旭
// 文件名: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:softwarepybind11-masterinclude',
     r'D:softwareAnacondainclude',
     r'D:projectthmysqlinclude'],
)

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++实现PyMysql的基本功能的文章就介绍到这了,更多相关c++ pymysql内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!