码迷,mamicode.com
首页 > 数据库 > 详细

Python连接Mysql数据库

时间:2018-12-22 14:57:34      阅读:218      评论:0      收藏:0      [点我收藏+]

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

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   

原文地址:https://www.cnblogs.com/carious/p/10160820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!