import MySQLdb as mdb
con=None
try:
con=mdb.connect(host="localhost",user="root",passwd="root",db="test")
cur=con.cursor()
cur.execute("SELECT VERSION()")
data = cur.fetchone()
print "Database version : %s " % data
finally:
if con:
con.close()
为什么将localhost改为127.0.0.1就可以成功连接,但是如果就是localhost的话就不能了呢?