在下面,可执行源代码我有一个小问题。那么你可以看到,我在名为nullable
的列中将some_text
设置为False。当我运行这个程序时,正确输入所有必要的注册数据,并在我应该输入文本的地方,但我只是按输入,我没有收到任何错误信息。我想,当我按下回车键(没有文字,空项目)时,我会收到来自SQLAlchemy的错误信息。但什么都没发生。 SQLAlchemy只执行commit ()
。之后,当我使用MySQL WorkBench
时,数据库中会出现一个空条目。
我做错了吗?
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Table, Column, Integer, String
''' setting up root class for declarative declaration '''
Base = declarative_base()
class SOME_TEXT(Base):
__tablename__ = "some_text"
id = Column(Integer, primary_key=True, unique=True)
some_text = Column(String(50), nullable=False, unique=True)
def __init__(self, Some_text):
self.some_text = Some_text
def main():
try:
dbms = raw_input('Enter database type: ')
dbdriver = raw_input('Enter database driver: ')
dbuser = raw_input('Enter user name: ')
dbuser_pwd = raw_input('Enter user password: ')
db_server_host = raw_input('Enter server host: ')
dbport = raw_input('Enter port: ')
db_name = raw_input('Enter database name: ')
url = '{}+{}://{}:{}@{}:{}/{}'.format(
dbms, dbdriver, dbuser, dbuser_pwd, db_server_host, dbport, db_name)
''' Create the engine '''
engine = create_engine(url, echo=True)
''' Create the schema and tables '''
Base.metadata.create_all(engine)
''' Create the Session class '''
Session = sessionmaker(bind=engine)
''' Create a new Session '''
session = Session()
''' Populate the database '''
enter_text = raw_input('Enter text: ')
some_text_table = SOME_TEXT(enter_text)
session.add(some_text_table)
''' Commit the changes: '''
session.commit()
except SQLAlchemyError as err:
print "err", err
if __name__ == "__main__":
main()