python 连接MySQL
1.安装MySQL
进入cmd,输入pip install PyMySQL,回车即可安装,我用的是python3
2.导入pymysql模块
在pycharm中输入import pymysql,如果安装之后仍然不能导入,
就在setting中手动安装PyMySQL,setting安装步骤请参考https://www.cnblogs.com/keqing1108/p/11936633.html
3.连接数据库
import pymysql
def conn_mysql():
conn = pymysql.connect(host='localhost', port=2020, user='username', password='password', db='db_name', charset='utf8')
cur = conn.cursor()
cur.execute('select * from TB_Name')
result = cur.fetchall()
cur.close()
conn.close()
print(result)
if __name__ == '__main__':
conn_mysql()
备注:port必须为int型,否则会报错:TypeError: %d format: a number is required, not str
charset的值为utf8,不是utf-8,
否则会报错:AttributeError: 'NoneType' object has no attribute 'encoding'