尝试插入MS SQL数据库,但我对此错误感到震惊:
INSERT语句与FOREIGN KEY约束冲突
原始错误(德语)
pypyodbc.IntegrityError: (u'23000', u'[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Die INSERT-Anweisung steht in Konflikt mit der FOREIGN KEY-Einschr\xe4nkung "FK_tCompanyLocation_tCompany". Der Konflikt trat in der Test-Datenbank, Tabelle "dbo.tCompany", column \'GUID\' auf.')
现在....我想我得到了错误...在插入tCompanyLocation时,company_guid(GUID)将不在tCompany表中,因为它将作为第二个插入我的脚本中。但是tCompany还需要company_location_guid(LocationGUID),所以我不能在之前执行....
在我看来,这就像鸡肉和鸡肉一样。 egg problem ...由于tCompanyLocation,我无法插入tCompany,反之亦然。
import uuid
import pypyodbc
company_guid = uuid.uuid4()
company_guid = str(company_guid).upper()
company_location_guid = uuid.uuid4()
company_location_guid = str(company_location_guid).upper()
position_guid = uuid.uuid4()
position_guid = str(position_guid).upper()
department_guid = uuid.uuid4()
department_guid= str(department_guid).upper()
experience_guid = uuid.uuid4()
experience_guid = str(experience_guid).upper()
people_guid = uuid.uuid4()
people_guid = str(people_guid).upper()
cnxn = pypyodbc.connect('DRIVER={SQL Server};SERVER=127.0.0.1;DATABASE=Test;UID=sa;PWD=password')
cursor = cnxn.cursor()
def insert_company_location():
sql = """
INSERT
INTO[dbo].[tCompanyLocation]
([GUID]
, [CompanyGUID]
, [LocationName]
, [Address1]
, [Address2]
, [City]
, [Zipcode]
, [Phone]
, [Fax]
, [TimeEntered]
, [TimeUpdated]
, [UserEnteredGUID]
, [UserUpdatedGUID]
, [UpdateHistory]
, [PhoneCountryCode]
, [FaxCountryCode]
, [CountryGUID]
, [CompanyLocationNotes]
, [RegionGUID]
, [Region2GUID])
VALUES
( """ + "\'" + company_location_guid + "\'" + """
, """ + "\'" + company_guid + "\'" + """
, 'New York, NY'
, 'Street 1'
, 'Street 2'
, 'New York'
, '10165'
, '+12121234123'
, '+12129124123'
, '2009-01-01 14:47:05.250'
, '2009-01-01 14:47:05.250'
, NULL
, NULL
, NULL
, '1'
, NULL
, '25B825CF-BDD0-11D5-93E2-00D0B7471F8B'
, NULL
, 'D2490D0A-140D-4D52-A57E-47909B6C222B'
, NULL)
"""
print(sql)
cursor.execute(sql)
def insert_company():
sql = """
INSERT
INTO[dbo].[tCompany]
([GUID]
, [CompanyTypeGUID]
, [BranchOfGUID]
, [CurrencyGUID]
, [CompanyName]
, [PrintName]
, [LocationGUID]
, [Website]
, [FeePercent]
, [FeeAmount]
, [FeeNotes]
, [Bio]
, [CompanyNotes]
, [CompanyDoNotPrint]
, [CompanyCode]
, [AlertMessage]
, [TimeEntered]
, [UserEnteredGUID]
, [TimeUpdated]
, [UserUpdatedGUID]
, [UpdateHistory]
, [CompanyLocationNotes]
, [ExternalDocument])
VALUES
( """ + "\'" + company_guid + "\'" + """
, NULL
, NULL
, '2104105B-31CA-11D4-BC2A-0050DA246141'
, 'IBM'
, NULL
, """ + "\'" + company_location_guid + "\'" + """
, 'http://www.ibm.com'
, '0.0000'
, '0,00'
, NULL
, NULL
, NULL
, '0'
, NULL
, NULL
, '2010-01-01 11:30:52.780'
, 'C9678062-0E21-4E2A-9707-4564E00B8678'
, '2010-02-01 11:31:53.000'
, 'C9678062-0E21-4E2A-9707-4564E00B8678'
, NULL
, NULL
, '0')
"""
cursor.execute(sql)
问题:
如何解决这个问题?我知道从Python生成GUID很糟糕,但是如果不在Python中实现它,我怎么能实现呢?如果有人可以告诉我,如何插入这两张表,那就太棒了。