Python SQLAlchemy 查询:AttributeError:“Connection”对象没有“contextual_connect”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19284012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:19:41  来源:igfitidea点击:

Python SQLAlchemy Query: AttributeError: 'Connection' object has no attribute 'contextual_connect'

pythonmysqldatabaseormsqlalchemy

提问by Michael

I am trying to follow this tutorialfrom SQLAlchemyon how to create entries in and query a MYSQL database in python. When I try and query the database for the first time following along in their adding new objectssection to test whether an object has been added to the database (see large code block below), I get the following error: AttributeError: 'Connection' object has no attribute 'contextual_connect'

我想按照这个教程,从SQLAlchemy如何创建条目,并在python查询MySQL数据库。当我在添加新对象部分中第一次尝试查询数据库以测试对象是否已添加到数据库时(请参阅下面的大代码块),我收到以下错误:AttributeError: 'Connection' object has no attribute 'contextual_connect'

I can query the database. For example, if I change the final line of code to our_user = session.query(User).filter_by(name='ed')it successfully returns a query object, but I cannot figure out how to get the object I entered into the database out of this query result.

我可以查询数据库。例如,如果我将最后一行代码更改为our_user = session.query(User).filter_by(name='ed')它成功返回一个查询对象,但我无法弄清楚如何从这个查询结果中获取我输入到数据库中的对象。

Similarly, if I try to loop over the results as they suggest in their queryingsection:

同样,如果我尝试按照他们在查询部分中的建议遍历结果:

for instance in session.query(User).order_by(User.id):
    print instance.name, instance.fullname

I get the same error. How can I fix this particular error and are there any other tutorials on using MYSQL in Python with SQLAlchemy that you could point me to?

我犯了同样的错误。我该如何修复这个特定的错误,是否还有其他关于在 Python 中使用 MYSQL 和 SQLAlchemy 的教程,您可以指点我吗?

My code:

我的代码:

import MySQLdb
from sqlalchemy import create_engine

db1 = MySQLdb.connect(host="127.0.0.1",
                      user="root",
                      passwd="****",
                      db="mydata")



from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

    def __repr__(self):
        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)


ed_user = User('ed', 'Ed Jones', 'edspassword') 

from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
Session.configure(bind=db1)

session = Session()
session.add(ed_user)

our_user = session.query(User).filter_by(name='ed').first()

Update/Working Code:

更新/工作代码:

(1) Change to SQLAlchemy engine as discussed by codeape below.

(1) 更改为 SQLAlchemy 引擎,如下面的 codeape 所讨论的。

(2) Remember to create the table: Base.metadata.create_all(engine)

(2)记得创建表: Base.metadata.create_all(engine)

(3) Use the "foolproof" version of the Userclass from SQLAlchemy's tutorial. Note to SQLAlchemy, we (at least I) feel like a fool and would like you to use to always use the foolproof version in the main body of your tutorial and not as an aside that a busy reader might skip over.

(3) 使用UserSQLAlchemy 教程中类的“万无一失”版本。请注意 SQLAlchemy,我们(至少我)觉得自己像个傻瓜,并希望您在教程的主体中始终使用万无一失的版本,而不是作为忙碌的读者可能会跳过的旁白。

All that yields working code:

所有产生工作代码的东西:

import MySQLdb
from sqlalchemy import create_engine

engine = create_engine("mysql://user:password@host/database")

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

from sqlalchemy import Column, Integer, String, Sequence

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    fullname = Column(String(50))
    password = Column(String(12))

    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

    def __repr__(self):
        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)



Base.metadata.create_all(engine)

ed_user = User('ed', 'Ed Jones', 'edspassword') 

from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
Session.configure(bind=engine)

session = Session()
session.add(ed_user)



our_user = session.query(User).filter_by(name='ed').first()

print(our_user is ed_user)

采纳答案by codeape

You must bind the session to a SQLAlchemy engine, not directly to a MySQLDb connection object.

您必须将会话绑定到 SQLAlchemy 引擎,而不是直接绑定到 MySQLDb 连接对象。

engine = create_engine("mysql://user:password@host/dbname")
Session.configure(bind=engine)

(You can remove your db1variable.)

(您可以删除db1变量。)

From the tutorial:

从教程:

The return value of create_engine() is an instance of Engine, and it represents the core interface to the database, adapted through a dialect that handles the details of the database and DBAPI in use.

create_engine() 的返回值是 Engine 的一个实例,它代表数据库的核心接口,通过处理数据库和使用中的 DBAPI 细节的方言进行调整。

See also https://docs.sqlalchemy.org/en/latest/orm/tutorial.html

另见https://docs.sqlalchemy.org/en/latest/orm/tutorial.html

回答by Vlad Bezden

from sqlalchemy.orm import sessionmaker

engine = create_engine("mysql://user:password@host/dbname")
Session = sessionmaker(bind=engine)

session = Session()