IntegrityError錯誤


   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, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Text, Index
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
from sqlalchemy.orm import sessionmaker

Base = 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 "<Sample('{0}','{1}')>".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.metadata
metadata.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下載     http://files.cnblogs.com/files/aliflycoris/db.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM