Python 使用相同的外键值将数据插入表中

Python 使用相同的外键值将数据插入表中,python,sql,sql-server,pyodbc,pypyodbc,Python,Sql,Sql Server,Pyodbc,Pypyodbc,我正在使用SQL Server、Python和PyODBC。 我的表格如下: tbl_User: id, owner tbl_UserPhone: id, number, user_id user_id是user的主键和UserPhone的外键。 我正在尝试使用PyODBC将两部不同的手机插入到同一个用户id。 这是我尝试过的不起作用的事情之一: cursor = connection.cursor() SQLCommand = ("INSERT INTO tbl_UserPhones"

我正在使用SQL Server、Python和PyODBC。 我的表格如下:

tbl_User: id, owner

tbl_UserPhone: id, number, user_id
user_id是user的主键和UserPhone的外键。 我正在尝试使用PyODBC将两部不同的手机插入到同一个用户id。 这是我尝试过的不起作用的事情之一:

cursor = connection.cursor()
SQLCommand = ("INSERT INTO tbl_UserPhones"
                    "(id,number,user_id)"
                    " VALUES (?,?,?)")
values = [userphone_index, user_phone,"((SELECT id from tbl_User where id = %d))" % user_id_index]
cursor.execute(SQLCommand, values)
cursor.commit()

根据您的评论,您在
tbl\u UserPhones
中有一个身份栏。根据列名,我猜是
ID

您得到的例外情况非常清楚-在insert语句之前,如果没有特别将
identity\u insert
设置为
on
,则无法将数据插入标识列。基本上,与标识栏混在一起是不好的做法。最好让Sql server使用其内置功能,并自动处理对标识列的插入

您需要将insert语句更改为不包含id列:

而不是

SQLCommand = ("INSERT INTO tbl_UserPhones"
                "(id,number,user_id)"
                " VALUES (?,?,?)")
values = [userphone_index, user_phone,"((SELECT id from tbl_User where id = %d))" % user_id_index]
试试这个:

SQLCommand = ("INSERT INTO tbl_UserPhones"
                "(number,user_id)"
                " VALUES (?,?)")
values = [user_phone,"((SELECT id from tbl_User where id = %d))" % user_id_index]

这就是解决方案。

您能解释一下
不起作用吗?你有错误吗?需要更多信息否,它只是跳过了cursor.commit()行。如果我是你,我会使用Python打印SQLCommand,然后尝试将该命令粘贴到SQLServer(如ManagementStudio)的控制台中,以查看错误是什么。我猜这就是您的tbl_UserPhones表的定义方式,但如果没有更多信息,就不可能知道。这就是我得到的:当identity_insert设置为OFF时,无法在表“tbl_UserPhones”中为identity列插入显式值。请澄清您的问题:(1)是
[tbl_UserPhone]。[id]
该表的标识列,如果是,它也是主键吗?(2) 您是否已经知道要插入到
[tbl\u UserPhone].[User\u id]
列中的
[tbl\u User].[id]
值?
SQLCommand = ("INSERT INTO tbl_UserPhones"
                "(id,number,user_id)"
                " VALUES (?,?,?)")
user_sqlCommand = cursor.execute("(SELECT id FROM tbl_User WHERE id = %d)" % user_index).fetchone()[0]
values = [userphone_index, user_phone, user_sqlCommand]