我正在使用以下代码进行连接:
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)")
我该如何解决呢?
答案 0 :(得分:1)
问题似乎是你的windwos主机上没有运行mysql服务器。您必须安装它(http://www.mysql.de/why-mysql/windows/)或必须选择其他服务器,如
db = MySQLdb.connect("my_mysql_host.mydomain.tld","root","root","test" )
多数民众赞成。
问候
答案 1 :(得分: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会帮助你:
How do I connect to a MySQL Database in Python?
最好的问候
答案 2 :(得分: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()