Python连接Mysql数据库
Posted cicarius
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python连接Mysql数据库相关的知识,希望对你有一定的参考价值。
1、环境配置及依赖安装
参考:https://pypi.org/project/mysqlclient/
sudo apt-get install libmysqlclient-dev
pip3 install mysqlclient
Note on Python 3 : if you are using python3 then you need to install python3-dev using the following command :
sudo apt-get install python3-dev # debian / Ubuntu
sudo yum install python3-devel # Red Hat / CentOS
2、使用Python连接数据库
查看资料:https://pypi.org/project/mysqlclient/
查看资料:https://mysqlclient.readthedocs.io/
3、用Python查询数据库
import MySQLdb
""" 获取连接 """
try:
conn = MySQLdb.connect(
host = "localhost",
port = 3306,
user = "dog",
passwd = "123456",
db = "news",
charset = ‘utf8‘
)
""" 获取数据 """
cursor = conn.cursor()
cursor.execute(‘SELECT * FROM `news` ORDER BY `created_at` DESC;‘)
rest = cursor.fetchone()
print(rest)
""" 关闭连接 """
conn.close()
except MySQLdb.Error as e:
print(‘Error: %s‘ %(e))
4、新增数据到数据库
以上是关于Python连接Mysql数据库的主要内容,如果未能解决你的问题,请参考以下文章