Python-无法连接到数据库
我正在学习python,我正在尝试连接到数据库: 操作系统Ubuntu 13.04 我已经运行了apache和localhost 我正在使用EclipsePydev 我已经安装了从这里下载的mysql连接器:一个.deb文件 我已经安装了sudo apt get install python mysqldb 列表项 这是我的代码,缩进正确:Python-无法连接到数据库,python,mysql,Python,Mysql,我正在学习python,我正在尝试连接到数据库: 操作系统Ubuntu 13.04 我已经运行了apache和localhost 我正在使用EclipsePydev 我已经安装了从这里下载的mysql连接器:一个.deb文件 我已经安装了sudo apt get install python mysqldb 列表项 这是我的代码,缩进正确: #!/usr/bin/python import MySQLdb try: db = MySQLdb.connect(host="localhos
#!/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,无法通过套接字连接到本地MySQL服务器
“/var/run/mysqld/mysqld.sock”2
如何解决这个问题?我已经解决了:我使用了另一个取自mysql使用示例的代码: 这是我现在的代码:
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()
我仍然不知道为什么我不能用另一种方式连接。从命令行运行时,mysql服务状态的结果是什么?当我在eclipse中运行时,控制台中会显示:2002,无法通过套接字“/var/run/mysqld/mysqld.sock”2连接到本地MySQL服务器回溯最近的调用上次:File/home/elfstone/Documents/workspace/FirstPythonProject/DB.py,cur.executeSELECT*中cur.executeSELECT*从您的_表中_NAME NAME错误:未定义名称“cur”,您是否引用了此选项?