我正在使用 this链接。
我已经将我的 cpp 文件与 Eclipse 连接到我的数据库,其中包含 3 个表(两个简单的表
Person
和 Item
第三个 PersonItem
连接它们)。在第三张表中,我使用了一个简单的主键,然后使用了两个外键:
CREATE TABLE PersonsItems(PersonsItemsId int not null auto_increment primary key,
Person_Id int not null,
Item_id int not null,
constraint fk_Person_id foreign key (Person_Id) references Person(PersonId),
constraint fk_Item_id foreign key (Item_id) references Items(ItemId));
所以,然后在 c 中使用嵌入式 sql,我希望一个人有多个项目。
我的代码:
mysql_query(connection, \
"INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8);");
printf("%ld PersonsItems Row(s) Updated!\n", (long) mysql_affected_rows(connection));
//SELECT newly inserted record.
mysql_query(connection, \
"SELECT Order_id FROM PersonsItems");
//Resource struct with rows of returned data.
resource = mysql_use_result(connection);
// Fetch multiple results
while((result = mysql_fetch_row(resource))) {
printf("%s %s\n",result[0], result[1]);
}
我的结果是
-1 PersonsItems Row(s) Updated!
5
但使用 VALUES (1,1,5), (1,1,8);
我愿意这样
-1 PersonsItems Row(s) Updated!
5 8
有人能告诉我为什么这没有发生吗? 亲切的问候。
最佳答案
我怀疑这是因为您的第一次插入失败并出现以下错误:
Duplicate entry '1' for key 'PRIMARY'
因为你试图将 1
插入到 PersonsItemsId
中两次,它是主键所以必须是唯一的(它也是 auto_increment 所以不需要指定一个值);
这就是受影响的行数为 -1 的原因,以及为什么在这一行中:
printf("%s %s\n",result[0], result[1]);
你只看到 5
因为第一条语句在值 (1,1,5)
已经被插入之后失败了,所以仍然有一行数据在表中。
我认为要获得您期望的行为,您需要使用 ON DUPLICATE KEY UPDATE语法:
INSERT INTO PersonsItems(PersonsItemsId, Person_Id, order_id)
VALUES (1,1,5), (1,1,8)
ON DUPLICATE KEY UPDATE Person_id = VALUES(person_Id), Order_ID = VALUES(Order_ID);
或者不指定 personsItemsID 的值,让 auto_increment 做它的事情:
INSERT INTO PersonsItems( Person_Id, order_id)
VALUES (1,5), (1,8);
关于c++ - sql Column with multiple values(cpp文件中的查询实现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19138213/