Python3下mysqlclient的安装和使用

1. 安装

1.1 下载wheel文件

网上搜多到的多数都是这种方案。从uci.edu按照自己的系统和Python版本现在wheel文件。比如我是Python3.6 32的版本。

uci.edu提供的wheel文件

1.2 安装

python -m pip install mysqlclient-1.4.6-cp36-cp36m-win32.whl
离线安装

2. 使用

2.1 查询

返回数据默认每一行做为一个tuple,多行返回的结构是tuple(tuple),可以通过制定db.cursor(MySQLdb.cursors.DictCourse)将返回结构修改为tuple(dict),列名为key,默认的Cursor类型为MySQLdb.cursors.Course

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

db = MySQLdb.connect(host="192.168.36.33", port=3306, db="db", user="user", password="pwd", charset='utf8')
# cursor = db.cursor(MySQLdb.cursors.DictCursor)
cursor = db.cursor()

cursor.execute("select * from client")
data = cursor.fetchall()

print(data, type(data))

# 关闭数据库连接
db.close()

输出数据

(
    (1, '大学生', 0, 'enterprise', 775895, 0, '', 1), 
    (2, '英语', 1, 'organization', 775894, 0, '', 2)
)

 <class 'tuple'>

2.2 参数化

MySQLdb.connect创建的连接默认不自动提交事务autocommit=False,执行后需要自己手动提交。通过tuple提交参数。

cursor.execute('''
      insert into client (name , parent_id, sub_system_type, group_id, is_deleted) values (%s,%s,%s,%s,%s)
''' ,  ('测试', 1, 'none', 1, 0))

db.commit()

2.3 批操作

cursor.executemany("insert into client (name , parent_id, sub_system_type, group_id, is_deleted) values (%s,%s,%s,%s,%s)" , (
    ('测试1', 1, 'none', 1, 0),
    ('测试2', 2, 'none', 2, 0),
))
db.commit()

9. 问题

9.1 尝试通过pip install安装mysqlclient失败

网上有说通过升级pip、setuptools后安装成功的,实际尝试下来都无效,这个问题还值得继续研究。

python -m pip install --upgrade pip
python -m pip install --upgrade setuptools
python -m pip install mysqlclient
command_error.png

提示需要Visual C++ 14.0,要想在线安装应该是选择安装相应的组件。

9.2 命令行pip安装成功,但是Pycharm里无法导入

这多数是因为pyenv引起的,命令行使用的python和Pycharm里的python不是同一个。

查看命令行python的安装位置

命令行python安装位置

通过File > Settings > Project > Project Interpreter查看当前Pycharm下使用的python

项目使用的Interpreter

切换成一致后问题就解决了。

参考文档

  1. https://mysqlclient.readthedocs.io/user_guide.html#mysqldb-user-s-guide
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。