【问题标题】:Python - can't connect to databasePython - 无法连接到数据库
【发布时间】:2013-08-11 01:34:44
【问题描述】:

我正在学习python,我正在尝试连接数据库:

  1. 操作系统 Ubuntu 13.04
  2. 我已经运行了 apache 和 localhost
  3. 我正在使用 eclipse pydev
  4. 我已经安装了从这里下载的mysql连接器:http://dev.mysql.com/downloads/connector/python/(一个.deb文件)
  5. 我已经安装了 sudo apt-get install python-mysqldb
  6. 列表项

这是我的代码(简单)(带有适当的缩进):

#!/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)")

我该如何解决这个问题?

【问题讨论】:

  • 从命令行运行service mysql status的结果是什么?
  • 当我在 eclipse 中运行时,在控制台中出现:(2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) ") Traceback(最近一次调用最后一次):文件“/home/elfstone/Documents/workspace/FirstPythonProject/DB.py”,第 20 行,在 cur.execute("SELECT * FROM YOUR_TABLE_NAME") NameError: name ' cur' 没有定义你指的是这个吗?

标签: python mysql


【解决方案1】:

我已解决:我使用了另一个取自 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()

我仍然不知道为什么我可以'以另一种方式连接。

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2011-06-16
    • 2022-09-27
    相关资源
    最近更新 更多