【python】利用python连接mysql数据库,判断是否可连接上

利用python连接mysql数据库,判断是否可连接上

引入的模块为MySQLdb

利用抛出异常来判断是否连接,如果连接上则会打印 link ok ,未连接则not link

#!/usr/bin/python
# -*- coding:UTF-8 -*-

import MySQLdb
import sys,commands,time
path=commands.getoutput(('pwd'))
fw=open(path+"/src/items/python_mysql/ini/link.ini","w")
try:
  db = MySQLdb.connect("localhost","root","password","computer_test",charset='utf8')

  cursor = db.cursor()
  cursor.execute("SELECT VERSION()")
  data=cursor.fetchone()
  db.commit()
  db.close()
  print(data)
  data="link ok"
  print(data)
  fw.write(str("yes"))
  
except:
  data="not link"
  print(data) 
  fw.write(str("no"))

fw.close()

 

你可能感兴趣的:(python)