首页 > 解决方案 > 为什么在这个 SQL 表中找不到这个列,当表定义时包含它?

问题描述

我正在尝试通过 python 3.8 创建两个 SQLite 数据库来存储用户信息。我有两个脚本定义数据库和一个用测试数据填充它。第一个数据库工作正常。它由脚本 create_logindb.py 定义:

from sqlalchemy import *
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
import bcrypt

engine = create_engine('sqlite:///upa.db', echo=True)
Base = declarative_base()

def create_hashed_password(plain_text_password):
    # Hash a password for the first time
    #   (Using bcrypt, the salt is saved into the hash itself)
    return bcrypt.hashpw(plain_text_password.encode('utf-8'), bcrypt.gensalt()).decode('utf8')

def check_hashed_password(plain_text_password, hashed_password):
    # Check hashed password. Using bcrypt, the salt is saved into the hash itself
    return bcrypt.checkpw(plain_text_password.encode('utf-8'), hashed_password.encode('utf-8'))


########################################################################
class User(Base):
    """"""

    def __init__(self, username, password, app_location):
        self.username = username
        self.password = password
        self.app_location = app_location

        
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    username = Column(String)
    password = Column(String)
    app_location = Column(String)
#----------------------------------------------------------------------

Base.metadata.create_all(engine)

我有一个用 create_redirectauthdb 定义的类似数据库:

engine = create_engine('sqlite:////Users/rpfhome/Documents/POS II/log in/ra.db', echo=True)
Base = declarative_base()



########################################################################
class Redirected_User(Base):
    """"""

    def __init__(self, username, hash_time, hash_value,user_ip,user_store):
        self.username = username
        self.hash_time = hash_time
        self.hash_value  = hash_value
        self.user_ip = user_ip#ip of user
        self.user_store = user_store#location of user data
        
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    username = Column(String)
    hash_time = Column(String)
    hash_value = Column(String)
    user_ip = Column(String)
    user_store = Column(String)

#----------------------------------------------------------------------

# create tables
Base.metadata.create_all(engine)

我正在创建测试帐户:


import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from create_logindb import *
from create_redirectauthdb import *
import bcrypt
import random
engine = create_engine('sqlite:///upa.db', echo=True)

# def create_hashed_password(plain_text_password):
#     # Hash a password for the first time
#     #   (Using bcrypt, the salt is saved into the hash itself)
#     return bcrypt.hashpw(plain_text_password.encode('utf-8'), bcrypt.gensalt())


# create a Session
Session = sessionmaker(bind=engine)
session = Session()

user = User("admin", create_hashed_password("password"), 'localhost:8000')
session.add(user)

user = User("python", create_hashed_password("python"), 'localhost:8001')
session.add(user)

user = User("jumpiness", create_hashed_password("python"),'localhost:8002')
session.add(user)

# commit the record the database
session.commit()

engine2 = create_engine('sqlite:////Users/rpfhome/Documents/POS II/log in/ra.db', echo=True)
Session2 = sessionmaker(bind=engine2)
session2 = Session()


user = Redirected_User("admin", 'uninitialized_datetime', str('%032x' % random.getrandbits(128)), '0.0.0.0','$Home/Documents/POS II/log in/')
session2.add(user)

user = Redirected_User("python", 'uninitialized_datetime', str('%032x' % random.getrandbits(128)), '0.0.0.0','$Home/Documents/POS II/log in/')
session2.add(user)

user = Redirected_User("jumpiness", 'uninitialized_datetime', str('%032x' % random.getrandbits(128)), '0.0.0.0','$Home/Documents/POS II/log in/')
session2.add(user)

# commit the record the database
session2.commit()


这只是我用来开始的一个玩具示例。第一个数据库 upa.db 已创建并很好地填充。尝试创建第二个数据库会产生错误:

...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) table users has no column named hash_time
[SQL: INSERT INTO users (username, hash_time, hash_value, user_ip, user_store) VALUES (?, ?, ?, ?, ?)]
[parameters: ('admin', 'uninitialized_datetime', '287cac9fcc2ab4760d8318190f182630', '0.0.0.0', '$Home/Documents/POS II/log in/')]
(Background on this error at: http://sqlalche.me/e/13/e3q8)

在这种情况下,错误的背景页面似乎没有多大帮助。我想知道为什么当数据库定义包含该列时,它说没有名为 hash_time 的列。我认为这可能与两个数据库都包含一个名为“users”的表有关,因此我在定义数据库的脚本中重命名了表“users2”,但随后出现错误,即在运行时没有名为 users2 的表用示例数据填充它的脚本。这对我来说也没有多大意义。我还尝试在第二个脚本中将 Base 的所有实例更改为 Base2 ,但这似乎没有效果。为什么用示例数据填充脚本中的数据库似乎与创建它的脚本中定义的数据库的结构不匹配?

标签: pythonsqlpython-3.xsqlitesqlalchemy

解决方案


正如@rfkortekaas 指出的那样,这是一个简单的错误。session2 是从第一个数据库的 Session() 创建的,在第二个数据库上不起作用。


推荐阅读