I have 5 tables where I use the same sequence's next value. The problem is, the subsequent tables gets a bigger value than the previous ones.
My code is like this:
String sql = "INSERT INTO table1(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "bar");
ps.executeUpdate();
sql = "INSERT INTO table2(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "tar");
ps.executeUpdate();
sql = "INSERT INTO table3(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "par");
ps.executeUpdate();
sql = "INSERT INTO table4(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "car");
ps.executeUpdate();
sql = "INSERT INTO table5(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "rar");
ps.executeUpdate();
My sequence is like this:
CREATE SEQUENCE "ID_SEQ" MINVALUE 1 MAXVALUE 9999999999 INCREMENT BY 1 START WITH 10 CACHE 20 NOORDER NOCYCLE ;
Now when I look at my tables, table1's ID is 10, but table2's ID is 11 and table3's ID is 12..... I want all the tables' IDs to be same. What should I do?
Thank you in advance.
edit: Had to include more tables than 2 to have more general question
Actually I found the answer online. I need to do this:
String sql = "select ID_SEQ.nextval from DUAL";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next())
int nextID_from_seq = rs.getInt(1);
And when I insert this value to database, I type this:
String sql2 = "INSERT INTO table1(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "tar");
ps.executeUpdate();
sql2 = "INSERT INTO table2(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "par");
ps.executeUpdate();
...
...
The first string sql is "select ID_SEQ.nextval from DUAL." That "DUAL" in the end is not table name or anything. It's just one of the given or provided functionality by oracle. I can get any sequence's nextval by using it.
You can use id_seq.currval for the second table. It will reuse the same id.
sql = "INSERT INTO table2(id, name) VALUES (id_seq.currval, ?)";
Related
I got this problem in my code java.sql.Exception: Parameter index out of range ( 2 number of parameters,which is 1).
This is my code:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t201835006","root","p73421231");
String mysql = "insert into books (bookName,Author,Perinting,Available) VALUES ('?','?',?,'True')";
PreparedStatement pstmt = conn.prepareStatement(mysql);
pstmt.setString(1,jTextField1.getText());
pstmt.setString(2,jTextField2.getText());
pstmt.setInt(3,Integer.parseInt(jTextField3.getText()));
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"insertion successful");
I tried :
"insert into books VALUES ('?','?',?,'True')";
"insert into books VALUES (?,?,?,'True')";
but it didn'T work.
My other codes in same project includes same databases but it works. I want to share iw for you:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t201835006","root","p73421231");
String sql ="insert into customerinfo values (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,jTextField3.getText());
pstmt.setString(2,jTextField1.getText());
pstmt.setInt(3,Integer.parseInt(jTextField2.getText()));
pstmt.setString(4,jTextField4.getText());
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"insertion successful");
new Menu().setVisible(true);
dispose();
I don't know why the first code doesn't work help me.
I'm taking a string and inserting it into a mySQL database field of type MEDIUMTEXT. When I print it out, there is a bunch of '-' characters and whitespace surrounding a slightly corrupted version of my original text. Am I doing this wrong?
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tripDB?characterEncoding=utf8","root","pass");
Statement stmt = con.createStatement();
query = "insert into trip (name, date, details) values (?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1, name); //Inserts correctly (varchar)
preparedStmt.setString(2, date); //Correct (varchar)
preparedStmt.setString(3, details); //Corrupted (MEDIUMTEXT)
preparedStmt.execute();
con.close();
So my issue is after I insert a new record in the database, I want to do a SELECT query that should include that new record. However, the data being returned excludes the newly added record. It seems like whenever I first open the connection, whatever is already in the database is what my program goes off. I hope this makes sense. All input is appreciated.
Update:
So here is the INSERT snippet
String DML = "INSERT INTO MEMBERS (FIRST_NAME, LAST_NAME, BIRTHDATE, DEATH_DATE, MARITAL_STATUS,"
+ " WEDDING_DATE, SPOUSE_NAME, MILITARY_SERVICE, DATE_JOINED, DEPARTURE_DATE, ACCEPTANCE_MODE, DEPARTURE_MODE,"
+ " RELATED_TO, NOTES) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(DML);
pstmt.setString(1, jTextField2.getText());
pstmt.setString(2, jTextField1.getText());
pstmt.setString(3, jTextField6.getText());
pstmt.setString(4, jTextField11.getText());
pstmt.setString(5, jTextField3.getText());
pstmt.setString(6, jTextField5.getText());
pstmt.setString(7, jTextField4.getText());
pstmt.setString(8, jTextField8.getText());
pstmt.setString(9, jTextField7.getText());
pstmt.setString(10, jTextField10.getText());
pstmt.setString(11, jTextField9.getText());
pstmt.setString(12, jTextField13.getText());
pstmt.setString(13, jTextField14.getText());
pstmt.setString(14, jTextArea1.getText());
pstmt.executeUpdate();
if (conn.getAutoCommit() == false)
conn.commit();
Now this is the SELECT snippet which if fired after the INSERT
pstmt=conn.prepareStatement("SELECT CONCAT(LAST_NAME, ', ', FIRST_NAME) AS NAME FROM MEMBERS ORDER BY LAST_NAME, FIRST_NAME");
rs=pstmt.executeQuery();
It is very likely that you have autocommit mode disabled and/or you are running the 2 queries (INSERT then SELECT) as a transaction.
Try turning autocommit mode on and then running the 2 queries again (INSERT then SELECT), it should work.
If you mean this
stmt.executeUpdate("insert into t1 ...");
ResultSet rs = stmt.executeQuery("select ... from t1");
then data inserted in statement 1 is always visible in statement 2, both in autocommit on and off modes.
It is only possibly that select does not see inserted records if you insert in one transaction, do not commit, and read in another transaction
Something like this can be done:
You can use an autoincrement column say call it serialID.
Insert data normally. When retrieving use MAX(serialID)
SELECT CONCAT(LAST_NAME, ', ', FIRST_NAME) AS NAME FROM MEMBERS ORDER BY
LAST_NAME, FIRST_NAME where serialID = (select max(serialID) from MEMBERS);
You'll have to do this in one transaction.
I still get error that I don't provide value for 1 parameter and I don't have idea what is wrong.
ps("INSERT INTO slide (presentation_id, duration, position, type) values (?, ?, ?, ?) ").set(this.getId()).set(slide.getDuration()).set(slide.getPosition()).set(slide.getType().ordinal()).update();
In table I only do not provide value for one column for which autoincrement is set.
Everything seems alright for me but please give any advice what might be wrong.
dont include the auto inc fieldin your column list.
ps("INSERT INTO slide (duration, position, type) values (?, ?, ?) ").set(slide.getDuration()).set(slide.getPosition()).set(slide.getType().ordinal()).update();
Try to do something more clean instead of this "train code"
This is an example:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
and here is the link to follow: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/
Using JDBC (Oracle) I need to insert about thousand rows into each of two tables. Something like this:
"INSERT INTO TABLE_A (A_ID, A_NAME, A_LAST_NAME) VALUES (MY_SEQUENCE.NEXTVAL, ?, ?)";
"INSERT INTO TABLE_B (B_ID, B_DESCRIPTION) VALUES (MY_SEQUENCE.CURRVAL, ?)";
The problem is that both tables are connected through common sequence, so that order of statements is important.
It would be quite easy if I had only one table. In that case I used code:
String insert = "Insert into TABLE_A(A_ID, A_NAME, A_LAST_NAME) values(MY_SEQUENCE.NEXTVAL, ?, ?)";
conn.setAutoCommit(false);
PreparedStatement ps = conn.prepareStatement(insert);
for(MyObject obj : myCollection) {
ps.setString(1, obj.getName());
ps.setString(2, obj.getLastName());
ps.addBatch();
}
ps.executeBatch();
conn.commit();
ps.close();
But this approach can work only with one prepared statment and thus with only one Insert. How can I provide a solution for this problem?
You can try
PreparedStatement ps = conn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
...
ps.executeBatch();
then
ResultSet rs = ps.getGeneratedKeys();
ps = conn.prepareStatement("INSERT INTO TABLE_B (B_ID, B_DESCRIPTION) VALUES (?, ?)");
for ( int counter =0;rs.next(); counter++ ) {
ps.setInt(1,rs.getInt(0));
ps.setString(2, myCollection.get(counter).getDescription());
ps.addBatch();
}
...
If I understand your problem correctly, you have a problem with NEXTVAL and CURRVAL since CURRVAL might change due to other DB use?
If so, you can change your code to this order:
currentNextVal = select NEXTVAL
INSERT into table_a with currentNextVal as the id
INSERT into table_b with the same currentNextVal
Did I understand your problem correctly?