python连接mysql失败怎么解决

Python (199) 2023-07-21 21:38:06

连接数据库,使用下面语句报错:

db=MySQLdb.connect("localhost","root","mysqladmin","testdb")

报错:

Traceback(mostrecentcalllast):
File"E:/PycharmProjects/file/hello1.py",line8,in<module>
db=MySQLdb.connect("localhost","root","mysqladmin","testdb")
File"E:\Python27\lib\site-packages\MySQLdb\__init__.py",line81,inConnect
returnConnection(*args,**kwargs)
File"E:\Python27\lib\site-packages\MySQLdb\connections.py",line187,in__init__
super(Connection,self).__init__(*args,**kwargs2)
_mysql_exceptions.OperationalError:(2003,"Can'tconnecttoMySQLserveron'localhost'(10061)")

相关推荐:《Python教程》

解决办法:将localhost 改为 127.0.0.1 即可。

db=MySQLdb.connect("127.0.0.1","root","mysqladmin","testdb")

下面是完整的连接程序:

#!\usr\bin\python
#coding=utf-8
importMySQLdb#已经安装上了二进制版数据库
#打开数据库连接
#这样子写是OK的:db=MySQLdb.connect(host="127.0.0.1",port=3306,user="root",passwd="mysqladmin",db="testdb")
#这样子写,会报错:db=MySQLdb.connect("localhost","root","mysqladmin","testdb")
db=MySQLdb.connect("127.0.0.1","root","mysqladmin","testdb")#这样子写是OK的
#使用cursor方法获取操作游标
cursor=db.cursor()
#使用execute方法执行sql语句
cursor.execute("selectversion()")
#使用fetchone()方法获取一条数据库
data=cursor.fetchone()
print"datebaseversion:%s"%data
#关闭数据库连接
db.close()
THE END

发表回复