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'

 


					


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM