我正在学习 python,我正在尝试连接到数据库:
- 操作系统 Ubuntu 13.04
- 我已经运行了 apache 和 localhost
- 我正在使用 eclipse pydev
- 我已经安装了从这里下载的mysql连接器:http://dev.mysql.com/downloads/connector/python/ (.deb 文件)
- 我已经安装了 sudo apt-get install python-mysqldb
- 列出项目
这是我的代码(简单)(具有适当的缩进):
#!/usr/bin/python
import MySQLdb
try:
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="root", # your password
db="Ayuda") # name of the data base
except Exception as a:
print a
cur = db.cursor()
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
for row in cur.fetchall() :
print row[0]
所以我得到这个错误:
(2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
如何解决这个问题?
最佳答案
我已经解决了:我使用了从mysql使用示例中获取的另一个代码:http://dev.mysql.com/doc/connector-python/en/myconnpy_example_connecting.html
这是我现在的代码:
import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(host="localhost",
user="root",
passwd="root",
db="Ayuda")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists")
else:
print(err)
else:
cur = cnx.cursor()
cur.execute("SELECT * FROM mitabla")
for row in cur.fetchall() :
print row[1]
cnx.close()
我仍然不知道为什么我可以通过其他方式连接。
关于Python - 无法连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167935/