SQLAlchemy无法连接到本地MySQL

时间:2014-02-27 22:55:40

标签: python sqlalchemy

我正在尝试使用SQLAlchemy来创建数据库,但是当我运行

meta.create_all()

我得到了

    super(Connection, self).__init__(*args, **kwargs2)
sqlalchemy.exc.OperationalError: (OperationalError) (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") None None

这是我的代码:

from sqlalchemy import *
from sqlalchemy.ext.declarative import *
from sqlalchemy.orm import *
from sqlalchemy.databases import mysql
from datetime import datetime
import logging
from operator import itemgetter
from collections import deque

#logging.basicConfig()
#logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

#meta = MetaData('sqlite:///database.sqlite3')
f = open("db.txt", "r") # db.txt should contain text like "mysql://realboy@localhost/realboy?charset=utf8&use_unicode=0"
db_path = f.read()
f.close()

db = create_engine(db_path)
meta = MetaData(db)
users = Table('users', meta,
  Column("id", Integer, primary_key=True),
  Column("username", String(100), unique=True),
  Column("password", String(100)),
  Column("explored_friends", Boolean, default=False),
  Column("exhausted_friends", Boolean, default=False),
  Column("explored_tweets", Boolean, default=False),
  Column("edge_count", Integer, default=0),
  Column("group", Integer, default=-1),
  mysql_charset='utf8'
)

meta.create_all()

1 个答案:

答案 0 :(得分:1)

您的MySQL服务器的套接字可能不在/tmp/mysql.sock,因此驱动程序无法连接。例如,我的位于/var/run/mysqld/mysqld.sock。 SQLAlchemy可能使用mysqclient驱动程序,该驱动程序带有unix_socket参数。要利用这一点,请尝试在连接URI中使用它,如下所示:

mysql://realboy@localhost/realboy?unix_socket=/var/run/mysqld/mysqld.sock

要找出服务器套接字的实际位置,请尝试查看/etc/mysql/my.cnf [或服务器用于配置的任何内容]