Python插入数据库提交失败,一直走IntegrityError错误,没打印错误信息(一定注意编码规范,记住打印错误信息),以为插不进去,弄了好久,最后打印了错误信息
(sqlite3.IntegrityError) samples.file_type may not be NULL [SQL: u'INSERT INTO samples (file_size, file_type, md5, crc32, sha1, sha256, sha512, ssdeep) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'] [parameters: (53, None, 'hello', 'crc32', 'sha1', 'sha256', 'sha512', None)]
提示为file_type不能为空,但是我建表的时候file_type设置的是不允许为空,而插入的时候file_type传入为NULL,所以Insert不成功,报错IntegrityError
from sqlalchemy import Column, Integer, Stringfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Text, Indexfrom sqlalchemy.exc import SQLAlchemyError, IntegrityErrorfrom sqlalchemy.orm import sessionmakerBase = declarative_base()class Sample(Base): """Submitted files details.""" __tablename__ = "samples" id = Column(Integer(), primary_key=True) file_size = Column(Integer(), nullable=False) file_type = Column(Text(), nullable=False) md5 = Column(String(32), nullable=False) crc32 = Column(String(8), nullable=False) sha1 = Column(String(40), nullable=False) sha256 = Column(String(64), nullable=False) sha512 = Column(String(128), nullable=False) ssdeep = Column(String(255), nullable=True) __table_args__ = Index("hash_index", "md5", "crc32", "sha1", "sha256", "sha512", unique=True), def __repr__(self): return "".format(self.id, self.sha256) def __init__(self, md5, crc32, sha1, sha256, sha512, file_size, file_type=None, ssdeep=None): self.md5 = md5 self.sha1 = sha1 self.crc32 = crc32 self.sha256 = sha256 self.sha512 = sha512 self.file_size = file_size if file_type: self.file_type = file_type if ssdeep: self.ssdeep = ssdeep engine = create_engine("sqlite:///cuckoo.db",echo=True) #返回连接引擎metadata = Base.metadatametadata.create_all(engine) #连接或者创建 #sample_mike = Sample("hello", "crc32", "sha1", "sha256", "sha512", 53, None, None) #非空数据不能传空
sample_mike = Sample("hello", "crc32", "sha1", "sha256", "sha512", 53, "aa", None)
Session = sessionmaker(bind=engine) session = Session() session.add(sample_mike) #数据库会话 try: session.commit() #提交 except IntegrityError as e: print e except SQLAlchemyError as e: print e
最后在网上看到一个比较有用的工具sqlite,查看db数据库
sqlite、db、insert.py下载