我正在使用SQL Server,Python,pypyodbc。 我有的表是:
tbl_User: id, owner
tbl_UserPhone: id, number, user_id
user_id是User的主键和UserPhone的外键。 我正在尝试使用pypyodbc将2个不同的手机插入同一个user_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()
答案 0 :(得分:0)
根据您的评论,您在tbl_UserPhones
中有一个标识列。根据列名称,我猜测它是ID
列。
您获得的异常非常明确 - 您无法在插入语句之前专门将identity_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]
答案 1 :(得分:0)
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]
这是解决方案。