1.所需库mysqlclient

2.遇到问题

2.1安装时出现错误:无法打开“mysql.h”

2.1.1解决方案

1.这是我从Stack Overflow上找的几个回答综合在一起得出的最OK解决方案:
2.所需要的文件:
    MySQL Connector / Python:https://downloads.mysql.com/archives/c-python/
    编译好的whl文件:https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient.Then
    我下的是mysqlclient-1.3.13-cp36-cp36m-win_amd64.whlmysql-connector-python-8.0.12-py3.6-windows-x86-64bit.msi 版本
    MySQL Connector / Python的安装会一闪而过

安装好后有两个新的包
安装好后有两个新的包

安装好后会遇到mysql-connector-python 8.0.12 requires protobuf>=3.0.0, which is not installed.直接安装protobuf即可,不安装也不影响根据需求而定

3.mysqlclient 官方GitHub主页

4.使用portable的接口MySQLdb

连接的构造函数connect(arg,\*args)
必填参数(host,user,passwd,db,port,)
对应参数(主机名称,用户名,密码,数据库名,mysqlserver的tcp端口,)
其他参考官方主页或源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import MySQLdb  #千万注意大小写
#获取连接,传入参数错误或连接远程主机断开等会抛出异常
try:
conn = MySQLdb.connect(
host = "localhost", #或127.0.0.1
port = 3306, #mysql默认端口3306
user = "root", #用户名
passwd = "feng", #密码
db = "flask_obj", #数据库名称
charset = "utf8" #数据库编码
)

cursor = conn.cursor() #创建游标
cursor.execute('select * from `test` ') #传入查询语句
result=cursor.fetchone() #查找一条数据,返回tuple
print(result) # (1, '2')
cursor.close() #关闭游标
conn.close() #关闭连接

except MySQLdb.Error as e:
print("Error: %s" % e)