python连接mysql失败怎么解决
连接数据库,使用下面语句报错:
db = MySQLdb.connect("localhost", "root", "mysqladmin", "testdb")
报错:
Traceback (most recent call last): File "E:/PycharmProjects/file/hello1.py", line 8, in <module> db = MySQLdb.connect("localhost", "root", "mysqladmin", "testdb") File "E:Python27libsite-packagesMySQLdb\__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "E:Python27libsite-packagesMySQLdbconnections.py", line 187, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
相关推荐:《Python教程》
解决办法:将localhost 改为 127.0.0.1 即可。
db = MySQLdb.connect("127.0.0.1", "root", "mysqladmin", "testdb")
下面是完整的连接程序:
#!usrinpython # coding=utf-8 import MySQLdb #已经安装上了二进制版数据库 #打开数据库连接 #这样子写是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("select version()") #使用fetchone()方法获取一条数据库 data = cursor.fetchone() print "datebase version : %s"%data #关闭数据库连接 db.close()
来源:PY学习网:原文地址:https://www.py.cn/article.html