0

我正在使用以下代码进行连接:

    import MySQLdb



db = MySQLdb.connect("localhost","root","root","test" )


cursor = db.cursor()


cursor.execute("SELECT * from student")


data = cursor.fetchone()
print "Database result : %s " % data


db.close()

我在运行文件时遇到以下错误:

Traceback (most recent call last):
File "C:/Python27/xsxs.py", line 5, in <module>
db = MySQLdb.connect("localhost","root","root","test" )
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

我该如何解决。

4

3 回答 3

1

问题似乎是您的windwos主机上没有运行mysql服务器。您要么必须安装它(http://www.mysql.de/why-mysql/windows/),要么必须选择另一个服务器,例如

db = MySQLdb.connect("my_mysql_host.mydomain.tld","root","root","test" )

而已。

问候

于 2013-03-22T09:21:19.477 回答
1

检查你的连接字符串:

db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="username", # your username
                      passwd="Pswrd", # your password
                      db="MyDB") # name of the data base

此 SO 将帮助您:

如何在 Python 中连接到 MySQL 数据库?

此致

于 2013-03-22T09:21:40.487 回答
0

使用 pip 安装 mysql 连接器,

sudo pip install mysql-connector-python

连接名为 TCS 的本地数据库并从名为 student 的表中选择数据的示例代码,

import mysql.connector    
cnx = mysql.connector.connect(user='root', password='1234',
                              host='localhost',
                              database='TCS')

try:
   cursor = cnx.cursor()
   cursor.execute("select * from student")
   result = cursor.fetchall()
   print result
finally:
    cnx.close()
于 2018-07-03T13:30:53.730 回答