python操作mysql数据库之获取连接及简单查询

  • A+
所属分类:网站首页

本文通过python实现mysql数据库的简单查询

1.获取连接

  1. import MySQLdb  
  2. try:  
  3.     conn = MySQLdb.connect(  
  4.         host = "127.0.0.1x",  
  5.         port = 3306,  
  6.         user = "root",  
  7.         passwd = "111111",  
  8.         db = "news",  
  9.         charset = 'utf8'  
  10.         )  
  11. except MySQLdb.Error as e:  
  12.     print('Error: %s' % e)  

2.获取数据

  1. cursor = conn.cursor()  
  2. cursor.execute('SELECT * FROM `news` ORDER BY `created_at` DESC;')  
  3. rest = cursor.fetchone()  
  4. print(rest)  

3.关闭连接

  1. conn.close()  
moonrong
  • 版权声明:本站原创文章,于2019年1月9日21:40:05,由 发表,共 458 字。
  • 版权声明: 本文由于2019年1月9日21:40:05 发表在 好派笔记,共 458 字。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: