新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python連接mysql失敗怎么解決
連接數(shù)據(jù)庫,使用下面語句報錯:

db = mysqldb.connect("localhost", "root", "mysqladmin", "testdb")
報錯:
Traceback (most recent call last): File "E:/PycharmProjects/file/hello1.py", line 8, indb = 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)")
相關推薦:《Python教程》
解決辦法:將localhost 改為 127.0.0.1 即可。
db = MySQLdb.connect("127.0.0.1", "root", "mysqladmin", "testdb")
下面是完整的連接程序:
#!\usr\bin\python
# coding=utf-8
import MySQLdb #已經(jīng)安裝上了二進制版數(shù)據(jù)庫
#打開數(shù)據(jù)庫連接
#這樣子寫是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 方法執(zhí)行sql語句
cursor.execute("select version()")
#使用fetchone()方法獲取一條數(shù)據(jù)庫
data = cursor.fetchone()
print "datebase version : %s"%data
#關閉數(shù)據(jù)庫連接
db.close() 分享文章:創(chuàng)新互聯(lián)Python教程:python連接mysql失敗怎么解決
網(wǎng)址分享:http://fisionsoft.com.cn/article/cccppid.html


咨詢
建站咨詢
