Creating multiple tuples in multiple tables

帅比萌擦擦* 提交于 2020-01-06 20:02:02

问题


I have a question on creating multiple tuples in multiple tables using Java.

Here are my tables.

create table department(

dept_name       varchar(20) primary key, 
building        varchar(15), 
budget      numeric(12,2)
);

create table student
(ID             int, 
 name           varchar(20) not null, 
 dept_name      varchar(20), 
 tot_cred       numeric(10,0),
 primary key (ID),
 foreign key (dept_name) references department(dept_name)
);

And what I am trying to accomplish is that the java program will prompt the user with

"How many tuples would you like in the Department Table?" User: 1000. "1000 tuples created in the Department table."

"How many Tuples would you like in the student table?" User: 500. "500 tuples created in the student table."

Now I can insert one tuple into department so say

"Insert into department ('CSI', 'TownHall', '120000')";

Then from here I do a

 Insert into student (id, name, dept_name,tot_cred)
             select '"+counts+"', 'Student"+counts+"', dept_name, '10' 
             from department      
             where    dept_name='CSI'.

Counts++ is in the while loop so there isn't duplicate PK's.

So I can create 10000 Tuples in the student table, but I cant create more than 1 tuple in the Department table because CSI can't be duplicated.

But if I don't insert atleast one tuple in the department table then I lose the Foreign key constraint.

Any thoughts?

PS. I'm not here for you guys to just do code just need an idea

Brandon


回答1:


Instead of having dept_name as a primary key, create another column DEPT_ID and set it as a primary key. You can increment that in the same way.

Also, consider using a PreparedStatement for your SQL updates

As a rule, your FK would point to the PK of another table. So when you have created DEPT_ID as a primary key, you would also need to modify your student schema to reflect this change

Edit: Based on your requirement, you can do something like this (although I don't know your exact requirement) & assuming the aforementioned change, you can do something like this

Create a PreparedStatement like this:

PreparedStatement pstmt = con.prepareStatement(INSERT INTO student(id, name, dept_id,tot_cred) values(?,?,?,?)");

Since you know the number of departments that you've, you can now create a loop to insert tuples into your department table and then use this information to insert into your student table, right? (This sounds more like a homework, so I would leave it to you to think of how to do this part)



来源:https://stackoverflow.com/questions/11633443/creating-multiple-tuples-in-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!