SELECT after INSERT statement? - java

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.

Related

how to check if a sql statement is ready to be executed?

How do I check if the statement can execute in my code? the second parameter won't be set if txtFirstName.getText() is empty.
String sql = "INSERT INTO Employees (id, firstName, lastName, adress, phone, email, photo, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = database.connection.prepareStatement(sql);
statement.setString(1, database.users.size() + 1 + "");
if (txtFirstName.getText().matches(""))
statement.setString(2, txtFirstName.getText());
statement.setString(3, txtLastName.getText());
statement.setString(4, txtAdress.getText());
statement.setString(5, txtPhone.getText());
statement.setString(6, txtEmail.getText());
statement.setString(7, txtPhotoURL.getText());
statement.setString(8, txtComment.getText());
statement.executeUpdate();
the second parameter won't be set if txtFirstName.getText() is empty.
Yes, it will; it will be set to an empty string. Whether that's valid for this specific query and table structure is beyond the realm of JDBC.
You need to check your constraints in advance, separately, and then either make the call or not.
You need an else condition to specify what to do if txtFirstName does not match the pattern, e.g.:
if (txtFirstName.getText().matches("")){
statement.setString(2, txtFirstName.getText());
}else {
throw new IllegalArgumentException("Invalid name pattern");
}
This will prevent the code from executing errorneous preparedstatement and throw an exception with appropriate error message.

How to get sequence.nextval from SQL in JDBC?

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, ?)";

SQL syntax error in Java Servlet

I tried to do this:
query1="INSERT INTO `users`(`email`, `password`, `login`, `familiya`, `name`, `otchestvo`, `age`, `country`, `city`, `mob`, `skype`) VALUES ("+user.getEmail()+","+user.getPassword()+","+user.getLogin()+","+user.getFamiliya()+","+user.getName()+","+user.getOtchestvo()+",11,"+user.getCountry()+","+user.getCity()+","+user.getMob()+","+user.getSkype()+")";
what did I do wrong? All "get" is not null, only syntax error.
I want to post image of database but I need 10 reputation...
all fields are varchar(15), age is int(2)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#mail.ru,12345,dima,Dmitriev,dima,Dmitrievich,11,Dmitrountry,Dmitriegrad,2020327' at line 1
put single quotes " ' " around your string values (varchar, text etc)
so
String query1="INSERT INTO users(email, password, login, familiya, name, otchestvo, age, country, city, mob, skype) VALUES ('"+user.getEmail()+"','"+user.getPassword()+"','"+user.getLogin()+"','"+user.getFamiliya()+"','"+user.getName()+"','"+user.getOtchestvo()+"',11,'"+user.getCountry()+"','"+user.getCity()+"','"+user.getMob()+"','"+user.getSkype()+"')";
not string related types DON't get single quotes....
A better way to do this however is using PreparedStatement,
String sql = "INSERT INTO users(email, password, login, familiya, name, otchestvo, age, country, city, mob, skype) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement preparedStatement = con.prepareStatement(sql)) {
preparedStatement.setString(1, user.getEmail);
preparedStatement.setString(2, user.getPassword);
preparedStatement.setString(3, user.getLogin());
preparedStatement.setString(4, user.getFamiliya());
preparedStatement.setString(5, user.getName());
preparedStatement.setString(6, user.getOtchestvo());
preparedStatement.setInt(7, 11);
preparedStatement.setString(8, user.getCountry());
preparedStatement.setString(9, user.getCity());
preparedStatement.setString(10, user.getMob());
preparedStatement.setString(11, user.getSkype());
preparedStatement.executeUpdate();
}

error java.sql.SQLException: Parameter index out of range

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/

Java JDBC - Multiple prepared statement bulk insert

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?

Categories