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.
Related
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);
}
}
I am trying to check if a user entered Username and password matches one in my data base however what ever I try the result set still comes up null. the sql varible is set to the username and the pass is set to the password however when ever i enter the correct details it shows up with no results
public boolean Login(){
boolean valid = true;
try {
String stmt = "SELECT * From TBLUser where User = ? and Password = ? ;";
PreparedStatement pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, sql); pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if(!rs.next()){
valid = false;
}
} catch (SQLException e) {
System.err.println("Error: "+e);
}
return valid;
}
Also, better practice:
public boolean Login(String asql, String apass){
boolean valid = true;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String stmt = "SELECT * From TBLUser where User = ? and Password = ? ";
pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, asql);
pstmt.setString(2, apass);
rs = pstmt.executeQuery();
valid = (!rs.next());
} catch (SQLException e) {
e.printStaceTrace();
} finally { // cleanup
try { rs.close(); } catch (Exception ex) {}
try { ps.close(); } catch (Exception ex) {}
}
return valid;
}
Use unit cap with " " to save your column-Table like
Create Table "TBLUser"{
"User" char...
"Password"...
}
similarly, your select query will change String
stmt = "SELECT * From \"TBLUser\" where \"User\" = ? and \"Password\" = ? "
This should work.
The problem with the application is not the code but the database as User one of the column names is a reserved word so this change fixed the problem thanks to #Grayson for all the help
public boolean Login(){
boolean valid = true;
try {
String stmt = "SELECT * From TBLUser where UserName = ? and Password = ? ;";
PreparedStatement pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, sql); pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if(!rs.next()){
valid = false;
}
} catch (SQLException e) {
System.err.println("Error: "+e);
}
return valid;
}
I am new to the site and Java.
Here's my issue:
I am trying to get a simple query working, but nothing happens.
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this,ex.getMessage());
}
try {
String nome = ricercaetichetta.getText();
rs = stmt.executeQuery("SELECT * From Giocatori Where Nome='" + nome + "'");
while(rs.next()) {
String nomeric = rs.getString("Nome");
risultati.setText("\n"+nomeric);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this,ex.getMessage());
}
}
I have a JTextField where you can write an input for WHERE clause.
Then I'd like to write my results in JTextArea.
When I run the program, it just lops without writing anything....
EDIT: After reading your comments, I tried this. It seems working, but is sensitive case....I'm going to look how to solve this. Thank you very much.
If there are problems with this code, please tell me, I'm learning.
try {
String SQL ="SELECT * From Giocatori Where Nome=?";
PreparedStatement preparedStatement = con.prepareStatement(SQL);
String nome= ricercaetichetta.getText();
preparedStatement.setString(1, nome);
System.out.println(nome); //try
rs = preparedStatement.executeQuery();
while (rs.next()) {
String firstName = rs.getString("Nome");
System.out.println(preparedStatement);
risultati.append(firstName+"\n");
}
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(this,ex.getMessage());
}
}
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.
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