连接数据库,使用下面语句报错:
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:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "E:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
解决办法:将localhost 改为 127.0.0.1 即可。
db = MySQLdb.connect("127.0.0.1", "root", "mysqladmin", "testdb")
下面是完整的连接程序:
#!\usr\bin\python # 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()
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试