Foriegn Key Auto Increment - java

I have a database called college with two tables; Students and Courses. Course_fk is a foriegn key of the primary key in Courses table. Now in my query for saving data, i am expecting the Course_fk to be have the id of the primary key in Courses table whenever data is saved into Courses table.
I am running a multiple query (i.e entering data into Students and Courses table at the same time) But i get an error saying "Course_fk doesn't have any default value".
Students
ID
Name
Course_fk
Courses
ID
Course_Name
Query to save data
String sql = "Insert into Students(Name) values (?)";
String query = "Insert into Guardians(Course_Name) values (?) ";
try{
pst1 = conn.prepareStatement(query);
pst1.setString(1, course_name.getText());
pst1.execute();
pst = conn.prepareStatement(sql);
pst.setString(1, name.getText());
pst.execute();

Based on your information I think that this insert will work for you:
INSERT INTO students (course_fk)
SELECT id FROM courses WHERE course_name = "coursename";
I did not check this in MySQL database.

Related

Cannot delete or update a parent row - Java

I teacher is trying to delete a row, which is used by a student.
But how can I delete this row anyway?
If the teacher wants to delete the lesson it should delete it anyway?
This is the function I have for the delete query:
con = DriverManager.getConnection ("jdbc:mysql://localhost:3307/lessons","root","");
String query = "DELETE FROM lessons WHERE Number= ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1,txtFieldNumber.getText());
pst.executeUpdate();
.
CREATE TABLE UserLogin(
Number INTEGER,
UserNumberINTEGER,
FOREIGN KEY (Number) REFERENCES termin(Number),
FOREIGN KEY (UserNumber) REFERENCES User(UserNumber)
);
CREATE TABLE lessons(
Number INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
LName VARCHAR(20)
);
CREATE TABLE User(
Name VARCHAR (20),
UserNUmber INTEGER NOT NULL PRIMARY KEY
);
You have to perform 2 separate deletes and in the right order using the same value for the Number parameter.
First delete from UserLogin with
DELETE FROM UserLogin WHERE Number = ?
And then use the command you have today
DELETE FROM lessons WHERE Number = ?
If you want to be sure both statements gets executed properly you can use manual commit like this
You can't use setString when the underlying column is int
Assuming your txtFieldNumber.getText() returns a number in String format, Try the following
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
Update:
Based on your question edit, looks like you are first trying to delete primary key in lessons which is being referenced in UserLogin table. This is the reason you're facing the error.
To overcome this, you may want to first delete in UserLogin table and then delete the corresponding rows in lessons table.
String query = "DELETE FROM UserLogin WHERE Number= ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
pst.executeUpdate();
String query2 = "DELETE FROM lessons WHERE Number= ?";
pst = con.prepareStatement(query2);
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
pst.executeUpdate();
This should solve your issue

How to insert a row in a nested table in Oracle with PreparedStatement

I created 2 types as OBJECT and a type of table and a nested table in my Oracle database. I know how to inset a row in table in cmd but I have no idea that how I can insert a row in this table with PreparedStatement in Java.
This is my table and type:
CREATE Or REPLACE TYPE item AS OBJECT
(
id number,
counter number
);/
CREATE Or REPLACE TYPE time AS OBJECT
(
year number,
month number,
second number
);
CREATE Or REPLACE TYPE Shoping_list AS TABLE OF item;
create table invoice(
id number NOT NULL PRIMARY KEY ,
list shoping_list,
dateIn date,
timeIn time,
totalCost number )
nested table list store as list_of_product;
I can insert with this code in cmd
insert into invoice(id,list,dateIn,timeIn,totalCost) values(seq_ID_invoice.nextval,
shoping_list(item(1,2),item(26,1)),TO_DATE('1396-04-11','YYYY-MM-DD'),time(11,25,40),7000);
and this my java code
preparedStatement = connection.prepareStatement("insert into invoice (id,list,dateIn,timeIn,totalCost) values ("+id+",?,?,?,?)");
seq_ID_invoice is Oracle Sequence. So oracle takes its value automatically. For rest you can use setInt, setString, setFloat, etc. methods available in PreparedStatement based on the types of columns defined inside your table.
Following sample code may help you.
PreparedStatement ps = connection.prepareStatement(
"insert into invoice(id, list, dateIn, timeIn, totalCost)"+
" values (seq_ID_invoice.nextval, shoping_list(item(?,?), item(?,?)), TO_DATE(?,'YYYY-MM-DD'), time(?, ?, ?), ?)");
ps.setInt(1, int_value_for_id_of_item_1);
ps.setInt(2, int_value_for_counter_of_item_1);
ps.setInt(3, int_value_for_id_of_item_2);
ps.setInt(4, int_value_for_counter_of_item_2);
ps.setString(5, string_value_for_date);
ps.setInt(6, int_value_for_year_of_time);
ps.setInt(7, int_value_for_month_of_time);
ps.setInt(8, int_value_for_second_of_time);
ps.setInt(9, int_bvalue_for_total_cost);
int rowCnt = ps.executeUpdate();
System.out.println(rowCnt+" rows affected.");
int_value_for_id_of_item_1, int_value_for_counter_of_item_1, ... these are java variables. You can defined variables of your choice or you can directly mention values in place of these variables.

PostgreSQL Insertion in JAVA via JSP Incrementing Primary Key

I am writing a JSP application where the user enters a food item and it is entered in a PostgreSQL database. I had no problems implementing this when the user manually had to enter the next primary key, but I removed this ability so that the primary key would be automatically assigned when the enter button is clicked. I would like the query to fetch the current maximum FID (Food ID) and set the new food item's FID to the previous + 1.
try {
conn = ConnectionProvider.getCon();
String sql = "select fid from project.food order by fid desc limit 1";
pst = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
status = pst.getResultSetType();
f.setFood_id(status + 1);
pst = conn.prepareStatement("insert into project.food values(?,?,?,?,?,?)");
pst.setInt(1, f.getFood_id());
pst.setString(2, f.getFood_name()); //set name
pst.setInt(3, f.getCount()); //set count
pst.setInt(4, f.getPrice_per_item()); //set price
pst.setInt(5, f.getThreshold()); //set threshold
pst.setString(6, "false");
status = pst.executeUpdate();
conn.close();
pst.close();
} catch (Exception ex) {
System.out.println(ex);
}
return status;
}
The first food item is successfully inserted into the database in row 1006, instead of the 7th row, which is the first available in the database. Additionally, the second insert fails due to the failure of the primary key to the incremented by 1. The program again tries to insert the next tuple in the same row and thus violates the primary key constraint.
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "food_pkey"
Detail: Key (fid)=(1006) already exists.
Make your primary key autoincrement in the database by declaring it SERIAL datatype (basically an auto incrementing INT) so a sequence is created to automatically assign values to it.
Then convert your update statement to specify all columns except for the primary key (i.e. insert into project.food(foo, bar, baz) values (?, ?, ?), and remove one ? placeholder and the pst.setInt(1,f.getFood_id()); line. This will insert values to all the other columns, and the primary key will be generated by the database.
This way you don't need to do a select when you want to insert (which was a really bad idea anyway), and you let the database do what it does best. You don't need to care about the value of the primary key after that.

How to insert multiple textfield data of a form into selected columns of a database table in java

I have a jinternal frame form with textfields. I am entering name and no to these textfields. I need to insert these data into my database table addstudents. In addstudent table there are more columns not only no and name column.
So I need to type select query inserting textfield data into selected columns.
String n = no.getText();
String nm = name.getText();
select no,name from addstudent insert into...
i can't find how to insert data to selected columns of the db table..
Please help me
Use a SQL INSERT statement, and use a Java PreparedStatement:
String n = no.getText();
String nm = name.getText();
String sql = "INSERT INTO addstudent ( no, name )" +
" VALUES ( ?, ? )";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, n);
stmt.setString(2, nm);
stmt.executeUpdate();
}

How to Auto increment a column in mysql table through java

i have table with 2 columns 1.column1 2.column2(its unique)
now through java coding i am inserting data through 2 methods
in the first method i want to insert data ,in this coumn1 filed should be auto increment(for new user)
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);
pstm.setInt(1, auto_incrmentvalue need to set);
pstm.setInt(2,column2);
in the second method insert data with what i want
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);
pstm.setInt(1, column1);
pstm.setInt(2,column2);
how to set auto increment value in the first method
NOTE:Here column1 is not a primary key
INSERT INTO table(column1) SELECT MAX(column1)+1 FROM table
This one worked for me
Please see INSERT...SELECT
Your query should be like this,
INSERT INTO table(column1, column2) SELECT MAX(column1)+1, 79 FROM table
More refined answer:
INSERT INTO
usertable(column1, column2)
SELECT CASE COUNT(column1)
WHEN 0 THEN 0
ELSE MAX(column1) END+1,
79 FROM usertable
This could be a more simple solution:
INSERT INTO usertable(column1, column2)
SELECT IFNULL(MAX(column1)+1,1),79 FROM usertable
Lets try this once (not tested)
INSERT INTO table(column1) SELECT count(column1)+1 FROM table
For ex,
INSERT INTO table(column1, column2) SELECT count(column1)+1, 79 FROM table
if you want the auto value of column1, don't set it, just let it get a defult value
INSERT INTO table (column2) values(?)

Categories

Resources