java.sql.SQLTransientConnectionException: HikariPool-1- connection is not available - java

I am a newbie assigned to build a hostel management application using HikariPool connection. Now, i sometimes get this error java.sql.SQLTransientConnectionException: HikariPool-1- connection is not available and once it happens, it messes up my application data. For instance, in my code below, i call the function paymentRecord() in my AssignRoom() to execute after a room is assigned.
I open and close connections in each functions(AssignRoom() and paymentRecord()) but sometimes, one of the functions fail to execute. It is either AssignRoom() executes correctly and paymentRecord() fails to execute or vice versa.
My code may be very bad but i am newbie trying to learn.
PS: Now i never had this issue when i was testing the application with good internet connection , but my Client did report this and he mostly has internet connectivity problem.
I sometimes think the internet connection might be a factor to my problem, if so why do i deal with this please?
Assigning Room
public void AssignRoom(){
try
{
java.sql.Date sqldate = new java.sql.Date(date.getDate().getTime());
conn = DBConnection.getConn();
String query = "Insert into AssignRoom(Floor,RoomNumber,Student,DateAssigned) values (?,?,?,?)";
PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, Floor.getSelectedItem().toString());
pst.setString(2, FindRoom.getSelectedItem().toString());
pst.setString(3, FindStd.getSelectedItem().toString());
pst.setDate(4, sqldate);
pst.execute();
if(seats.getText().equals("0")){
JOptionPane.showMessageDialog(null, "Room is fully occupied");
}
else
{
JOptionPane.showMessageDialog(null, "Room Successfully Assigned");
UpdateAvailableBeds();
paymentRecord();
conn.close();
JOptionPane.showMessageDialog(null, "Please wait...Processing payment");
navToPayment();
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
Payment Record
public void paymentRecord()
{
try
{
java.sql.Date sqldate = new java.sql.Date(date.getDate().getTime());
System.out.println("Cheking "+sqldate);
System.out.println("Cheking "+FindRoom.getSelectedItem().toString());
System.out.println("Cheking "+FindStd.getSelectedItem().toString());
conn = DBConnection.getConn();
String query = "Insert into PaymentRecords(Student_Name,Room_Number,DateAssigned,Total_Amount,Paid,Balance) values(?,?,?,?,?,?)";
String sql = "select Price from Rooms where RoomNumber =" +FindRoom.getSelectedItem()+ " and Floor ='"+Floor.getSelectedItem().toString()+"'";
PreparedStatement pst = conn.prepareStatement(query);
PreparedStatement pst1 = conn.prepareStatement(sql);
// ResultSet rs = pst.executeUpdate(query);
ResultSet rs1 = pst1.executeQuery(sql);
while(rs1.next())
{
FullAmount = rs1.getString("Price");
Price = Float.parseFloat(FullAmount);
Rem = Float.parseFloat(AmtPaid.getText());
Balance = Price - Rem;
System.out.println("Cheking "+FullAmount);
}
pst.setString(1, FindStd.getSelectedItem().toString());
pst.setString(2, FindRoom.getSelectedItem().toString());
pst.setDate(3, sqldate);
pst.setString(4, FullAmount);
pst.setString(5, AmtPaid.getText());
pst.setFloat(6, Balance);
pst.execute();
pst1.execute();
conn.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}

Related

Unable to execute prepared Statement from DAO

So currently Im trying to do get the auto-incremented primary key by following this answer
Primary key from inserted row jdbc? but apparently the program can't even reach that line and the error appeared on the ps.executeQuery() line after debugging the program, the error it display was only "executeQuery" is not a known variable in the current context. that line, which didn't make sense to me. So how do I go pass this hurdle?
public static int createNewLoginUsers(String newPassword, String newRole) throws SQLException{
Connection conn = DBConnection.getConnection();
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
int id = 0;
try{
String sql = "INSERT into Login(password, role) VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, newPassword);
ps.setString(2, newRole);
ps.executeUpdate();
st = conn.createStatement();
rs = st.executeQuery("SELECT * from Login");
rs.last();
System.out.println(rs.getInt("username"));
id = rs.getInt("username");
rs.close();
} finally{
try{
conn.close();
}catch(SQLException e){
System.out.println(e);
}
}
return id;
}
The part of the method which calls the createNewLoginUsers method
if(newPasstxtfld.getText().equals(retypeNewPasstxtfld.getText())){
//update into database
try {
int username = CreateUsersDAO.createNewLoginUsers( (String) newUserRoleBox.getSelectionModel().getSelectedItem(), newPasstxtfld.getText());
Alert confirmation = new Alert(Alert.AlertType.INFORMATION);
confirmation.setHeaderText("New User Details has been created. Your username is " + username);
confirmation.showAndWait();
} catch (SQLException e) {
}
EDIT:
Databases table added and it's in the provided link below
https://imgur.com/a/Dggp2kc and edit to the codes instead of 2 try blocks in one method i have placed it into a different similar method, updated my codes to the current one I have.

JDBC error : can not issue executeupdate() for selects

Good day ,
While I am trying to update data after inserting new ones in the database,
This message is showing for me
can not issue executeupdate() for selects
I have checked tutorialspoint.com and codejava and the codes for both update and select are the same and the program is issuing the statement above
Here is my codes
String Sql="Select * from training where trainID=? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("traTitle"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
String Sql="Select * from training where traTitle =? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("trainID"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
String Sql= "UPDATE training SET traTitle ='"+ jTextField2.getText()+"', Type = "+(String) jComboBox1.getSelectedItem()+"', SDate = '"+sqlDate+"', Edate = '"+sqlDate2+"', location = '"+jTextField3.getText()+"',provider = '"+(String) jComboBox1.getSelectedItem()+"',related = '"+jTextArea1.getText()+"',benefits = '"+jTextArea2.getText()+"'important = '"+jTextArea3.getText()+"' WHERE trainID = "+jTextField1.getText()+"";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
Statement st = con.createStatement();
int i =ps.executeUpdate();
if (i>0)
{
JOptionPane.showMessageDialog(null, "Data is Saved");
}
else {
JOptionPane.showMessageDialog(null, "Data is not Saved");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
JOptionPane.showMessageDialog(null, e);
}
Any Solution ?
Statement st = con.createStatement();
int i = ps.executeUpdate();
The problem is here. You are creating a new, unused, Statement, and then trying to call executeUpdate() on the previously prepared statement, which was a SELECT.
This would have been avoided by correctly scoping the variables concerned as method-local. None of them should be instance or static members.

Rollback does not work

I want to rollback all records have been inserted to table when exception occurs.
but conInsert.rollback() doesn't work.
Maybe I miss some code?
Here is my code
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(connectionUrl);
//con.setAutoCommit(false);
Statement st = con.createStatement();
String querySelectOrderInTp = "SELECT order_in_tp_id, order_in_tp_qty, order_in_tp_price, order_in_tp_article_tc_id, order_in_tp_warehouse_tc_id, inv_stock_tp_id, inv_stock_tp_qty_available from order_in_tp LEFT JOIN inv_stock_tp on(order_in_tp_warehouse_tc_id=inv_stock_tp_whouse_current_id AND order_in_tp_article_tc_id=inv_stock_tp_article_tc_id AND order_in_tp_price=inv_stock_tp_price) where order_in_tp_pick_up_timestamp = 'A' AND order_in_tp_date = '2013-06-11' GROUP BY order_in_tp_id;";
ResultSet rs = st.executeQuery(querySelectOrderInTp);
String queryUpdateInvStockTp = "INSERT INTO inv_stock_tp (cre_tms,upd_tms,cre_usr,upd_usr,version,usr_act,inv_stock_tp_id,inv_stock_tp_key, inv_stock_tp_whouse_current_id,inv_stock_tp_article_tc_id,inv_stock_tp_qty_available,inv_stock_tp_qty_min,inv_stock_tp_price) VALUES (NOW(),NOW(),'demo2','demo2',1,'A',null,'AAAA',?,?,?,0,2000.0000)";
conInsert = DriverManager.getConnection(connectionUrl);
conInsert.setAutoCommit(false);
ps = conInsert.prepareStatement(queryUpdateInvStockTp);
String queryUpdateOrderInTp = "UPDATE order_in_tp set order_in_tp_pick_up_timestamp = ? WHERE order_in_tp_id = ?";
psUpdate = con.prepareStatement(queryUpdateOrderInTp);
while(rs.next()) {
Integer qty = rs.getInt(7) - rs.getInt(2);
ps.setString(1, rs.getString(5));
ps.setString(2, rs.getString(4));
ps.setString(3, rs.getString(2));
ps.execute();
psUpdate.setString(1, "A");
psUpdate.setString(2, rs.getString(1));
psUpdate.execute();
ps.clearParameters();
psUpdate.clearParameters();
}
conInsert.commit();
} catch (Exception e) {
e.printStackTrace();
if (conInsert != null) {
try {
System.err.print("Transaction is being rolled back");
conInsert.rollback();
} catch (SQLException excep) {
excep.printStackTrace();
}
}
}
I make an exception in last record but all record before it still have been inserted.
By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. I dont know java, but make sure that You have the START TRANSACTION statement, and then COMMIT or ROLLBACK.

MsAccess SQL Exception Too few parameters

Currently making a java program that grabs data off of a MSAccess Database and some of these errors are extremely frustrating. I keep getting this SQL.Exception : Too few parameters. Expected 1 error on the last remaining bugs in this program.
Little background on the db: It has 3 tables (A player table (11 columns), a team table (3 columns), and an Opponent table (6 columns).
These are both of the functions and I am fairly certain the problem lies in here somewhere
conn = Connect.ConnectDB();
String sql = "insert into Player ("+"PlayerLastName,"+"PlayerFirstName,"+"Position)"+ "values("+txtid.getText()+ ",'"+txtname.getText()+"','"+txtaddress.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.executeQuery();
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
or this function
String sql = "select * from Player where PlayerLastName = " +txtid.getText()+ "";
String pine = null;
try{
pst = conn.prepareStatement(sql);
ResultSet res;
res = pst.executeQuery();
pine.equalsIgnoreCase(jTable1.getModel().getValueAt(rowsu, 10).toString());
while(res.next()){
JOptionPane.showMessageDialog(null, txtname + " " + txtid.getText() + " has a total of " +"4");//+ pine);//res.getInt("Penalties") );
}
UpdateJTable();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
For one thing, it looks like you're missing single quotes around the last name in the insert statement.
There may be other errors as well, that's just the first thing I noticed.
This should be pretty easy to debug if you just log the sql string before executing it.
EDIT
I think your calls to setString() are also a problem. Here is how you should do this:
conn = Connect.ConnectDB();
String sql = "insert into Player (PlayerLastName, PlayerFirstName, Position) values(?, ?, ?)";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
pst.execute();
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

Problems with PreparedStatement - Java

Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again

Categories