簡體   English   中英

將數據從excel工作表轉儲到mysql數據庫時出錯

[英]getting error while dumping the data from excel sheet to mysql database

我從excel表導入特定的數據,並將該數據轉儲到mysql數據庫。 但是在這樣做的時候我得到了錯誤

       $ python dtz_db.py
dtz_db.py:43: Warning: Field 'datetime' doesn't have a default value
  cursor.execute(query2, values2)
dtz_db.py:43: Warning: Data truncated for column 'lease_start_date' at row 1
  cursor.execute(query2, values2)
dtz_db.py:43: Warning: Data truncated for column 'lease_end_date' at row 1
  cursor.execute(query2, values2)
dtz_db.py:43: Warning: Incorrect integer value: '' for column 'lease' at row 1
  cursor.execute(query2, values2)
dtz_db.py:43: Warning: Incorrect integer value: '' for column 'leased' at row 1
  cursor.execute(query2, values2)
Traceback (most recent call last):
  File "dtz_db.py", line 44, in <module>
    cursor.execute(query1, values1)
  File "c:\Python27\lib\site-packages\MySQLdb\cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "c:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defau
lterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.IntegrityError: (1452, 'Cannot add or update a child row: a fo
reign key constraint fails (`dtz_new`.`property_property`, CONSTRAINT `lease_id_
refs_id_816819bc` FOREIGN KEY (`lease_id`) REFERENCES `property_propertylease` (
`id`))')

我的python文件是此cod,用於從excel文件中選擇特定數據並將該數據轉儲到mysql數據庫

import xlrd
import MySQLdb
book = xlrd.open_workbook("dtz11.xls")
sheet = book.sheet_by_name("Sheet1")
database = MySQLdb.connect (host="localhost", user="root", passwd="", db="dtz_new")
cursor = database.cursor()
query1 = """INSERT INTO property_property( name,  inpection_date) VALUES(%s, %s )"""
query2 = """INSERT INTO property_propertylease( lease_start_date,  lease_end_date, lease, leased) VALUES(%s, %s, %s, %s)"""
for r in range(1, sheet.nrows):
    gaurav2         = sheet.cell(r,1).value
    gaurav3         = sheet.cell(r,2).value
    gaurav8         = sheet.cell(r,18).value
    gaurav9         = sheet.cell(r,19).value
    gaurav10        = sheet.cell(r,20).value
    gaurav11        = sheet.cell(r,21).value
    values1 = (gaurav2, gaurav3)
    values2 = (gaurav8, gaurav9, gaurav10, gaurav11)
    cursor.execute(query2, values2)
    cursor.execute(query1, values1)
cursor.close()
database.commit()
database.close()
print "dumped successfully"
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print "I just imported "+ columns+ " columns and "+ rows+" rows to MySQL!"

我的數據庫表架構是 在此處輸入圖片說明

請幫助我解決此問題,,,,非常感謝

您的插入語句斷言將有8個變量提供給數據庫,但您只給了它7。從那里開始。

(我既不知道python也不知道excel交互,所以我還沒有發布任何代碼。我懷疑問題完全出在該INSERT語句中。)

編輯:因此,外鍵約束錯誤意味着根據您的架構,property_property的lease_id指向另一個表中的數據(property_propertylease)。 由於您沒有給第二張表任何數據,因此插入失敗。

換句話說,您的插入語句將填充父表。 父表正在嘗試引用不存在的子表中的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM