目录
-
前言
mac(10.12.6)下最近要用Python(2.7)写一个脚本,涉及到连接mysql数据库。以前在mac上python连接mysql是没有问题的,这次换了新的mac本,发现连接时提示报错,代码中提示“MySQLdb”模块没有安装。OK,那就pip install MySQLdb安装吧。
然后,就发现一路不顺畅。又是要在本机安装mysql,又是下载MySQL-python包的, 又是修改***配置路径的………………(网上类似文档太多了,摘录一份参考过的:https://www.jianshu.com/p/71cf187598ce
记得在自己上一个mac本下没有复杂过。这种安装方式简直无力吐槽。好吧,换一种其他方式连接mysql吧,何必一定使用MySQLdb模块!
-
正文
直接show code。这里,使用的模块是PyMySQL,直接“pip install PyMySQL”即可。
# coding=utf-8
import pymysql.cursors
# mysql init
def get_cursor():
connection = pymysql.connect(host='10.0.10.10',
user='root',
password='123456',
db='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
return connection.cursor()
def execute():
cursor = get_cursor()
cursor.execute("select id, request_body from record where cluster = 'op' limit 1")
result = cursor.fetchall()
for row in result:
request_body = row["request_body"]
print request_body
if __name__ == "__main__":
execute()
-
参考文档
《Connect MySQL with Python Windows/Linux/Mac OSx》:https://koraykaraman.com/blog/3575/Connect-MySQL-with-Python-Windows-Linux-Mac-OSx