未定义 'BoundMetaData
我找到了这个教程
当我编译的时候,出现了错误信息
The debugged program raised the exception unhandled NameError
"name 'BoundMetaData' is not defined"
我使用的是最新的sqlAlchemy。
我该怎么解决这个问题呢?
看完这个之后,我根据最新版本的sqlAlchemy做了一些修改:
from sqlalchemy import *
engine = create_engine('mysql://root:mypassword@localhost/mysql')
metadata = MetaData()
users = Table('users', metadata,
Column('user_id', Integer, primary_key=True),
Column('name', String(40)),
Column('age', Integer),
Column('password', String),
)
metadata.create_all(engine)
i = users.insert()
i.execute(name='Mary', age=30, password='secret')
i.execute({'name': 'John', 'age': 42},
{'name': 'Susan', 'age': 57},
{'name': 'Carl', 'age': 33})
s = users.select()
rs = s.execute()
row = rs.fetchone()
print 'Id:', row[0]
print 'Name:', row['name']
print 'Age:', row.age
print 'Password:', row[users.c.password]
for row in rs:
print row.name, 'is', row.age, 'years old
但是它还是报错了
raise exc.DBAPIError.instance(statement, parameters, e, connection_invalidated=is_disconnect)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' \n\tPRIMARY KEY (user_id)\n)' at line 5") '\nCREATE TABLE users (\n\tuser_id INTEGER NOT NULL AUTO_INCREMENT, \n\tname VARCHAR(40), \n\tage INTEGER, \n\tpassword VARCHAR, \n\tPRIMARY KEY (user_id)\n)\n\n' ()
3 个回答
2
我觉得你需要指定一下你的 password
字段的长度。
Column('password', String(100))
MySQL 不允许没有长度限制的 varchar 列。如果你需要这样,可以使用 sqlalchemy 的数据类型 Text
来代替。
25
这个教程的解决办法就是用 MetaData
代替 BoundMetaData
。因为 BoundMetaData
已经不再使用了,换成了 MetaData
。
为了避免将来再出现这样的错误,建议你去看看 官方 的教程,就像 Nosklo
说的那样。
from sqlalchemy import *
db = create_engine('sqlite:///tutorial.db')
db.echo = False # Try changing this to True and see what happens
metadata = MetaData(db)
"""
Continue with the rest of your Python code
"""
19
这个教程是关于SQLAlchemy 0.2版本的。现在的版本是0.5.7,所以这个教程已经非常过时了。
建议你去看看官方的教程。
编辑:
现在你问的问题完全不同。你应该另起一个问题,而不是在这个问题上进行编辑。
你现在的问题是
Column('password', String),
没有为这个列指定大小。
试试
Column('password', String(20)),
来解决这个问题。