[Python] python connected using mysql database, determines whether the connection

Python mysql database using the connection, it is determined whether the connection

Module is introduced MySQLdb

Use to determine whether an exception is thrown connection, if the connection is printed on the link ok, not link unconnected

#!/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()

 

Published 201 original articles · won praise 46 · views 90000 +

Guess you like

Origin blog.csdn.net/rong11417/article/details/104821186
Recommended