这是我第一次在Java ee做一个更大的应用程序,我想做一个书店,这是我的数据库的样子:
Book:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null
Cart:
-id:(int) primary key, autoincrement, not null
和
Artical:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null,
- cart_id:(int) foreign key referencing cart
我已经有一些书在书表,文章和购物车是空的,所以想法是当用户点击按钮“添加到购物车”我想插入id在购物车表和数据(书)在文章表的基础上的书被点击。 下面是我的INSERT语句的样子:
insert into Cart (id) values(null);
INSERT INTO Artical(id,title,price,cart_id)
VALUES(null,
'some book',
20,
(select Cart.id from Cart join Artical AS ar ON Cart.id = ar.cart_id));
我得到错误cart_id不能为空
。 是我的说法错了还是整个设计错了?
尝试避免id的null值,并使用select和文字值。 而不是asubqiery col cart_id
INSERT INTO Artical(title,price,cart_id)
select 'some book',20, Cart.id
from Cart
join Artical as ar on Cart.id = ar.cart.id
select Cart.id from Cart join Artical as ar on Cart.id=ar.cart_id
行返回的结果为空或零。 这似乎很明显-这里的想法肯定是使用新创建的购物车行的ID,这是。。 不是你怎么做的,我有点不明白你为什么会这么认为。
JDBC有一些工具来获取新行中自动生成的条目,例如PreparedStatement
的GetGeneratedKeys
方法。
更一般说来,不要使用NULL作为'Please auto-increment my column here‘的占位符--这是特定于db的。 为什么不insert into Cart()values();
? 更简单,更短。 Artical也一样(你不是说‘文章’吗?) -插入文章(标题,价格,cart_id)值('some book‘,20,idIGotFromGetGeneratedKeys);