当前位置:Gxlcms > 数据库问题 > Python连接Mysql数据库

Python连接Mysql数据库

时间:2021-07-01 10:21:17 帮助过:3人阅读

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数据库

标签:erro   使用   get   mys   local   note   com   create   centos   

人气教程排行