I'm develop an application to connect MySQL via JDBC. In an action, I need to execute two queries, sql to read, and sql to update.
To make sure, sql to read query would be executed first, and sql to update to be executed later, I use JDBC transaction. But somehow, the problem is, mysql execute 2nd query first, and then the first read query.
Looking for suggestions. Many thanks.
// Sql connection
Connection conn = null;
Statement stmt = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatementUpdate = null;
String sql = "SELECT item_name, item_detail FROM Order_Printing where kitchen_id = ? and order_printed = ?";
String sqlFlag = "UPDATE order_printing set order_printed = 1 where kitchen_id = ?";
try {
// Register JDBC driver (Note to add mysql connector jar file)
Class.forName("com.mysql.jdbc.Driver");
// Step 3: open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
conn.setAutoCommit(false); // Disable auto-commit mode
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 4);
preparedStatement.setInt(2, 0);
ResultSet rs = preparedStatement.executeQuery();
//
preparedStatementUpdate = conn.prepareStatement(sqlFlag);
preparedStatementUpdate.setInt(1, 4);
preparedStatementUpdate.executeUpdate();
int startingPos = 10;
int orderNumber = 1;
while (rs.next()) {
String item_name = "Order " + orderNumber++ + ": ";
item_name += rs.getString("item_name");
String item_detail = rs.getString("item_detail");
startingPos += 20;
g.drawString(item_name, 0, startingPos);
startingPos += 20;
g.drawString(item_detail, 0, startingPos);
}
conn.commit();
} catch (SQLException se) {
se.printStackTrace();
} catch (ClassNotFoundException se) {
se.printStackTrace();
} catch (Exception se) {
se.printStackTrace();
} finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
Try executing rs.next() while loop BEFORE you call preparedStatementUpdate.executeUpdate();
Related
I am trying to make a ATM Project in Net beans but I am stack here.
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
Statement st = null;
if (accNumField.getText().isEmpty() || pinField.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please fill in the Fields");
}else{
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankmanagement", "root", "");
String query = "Select from * clients where AccNum='"+accNumField.getText()+"' and PIN="+pinField.getText()+"";
**st = con.createStatement();
rs= st.executeQuery(query); **
if(rs.next()){
new MainMenu().setVisible(true);
this.dispose();
}else{
}
} catch (Exception e) {
enter image description hereCan someone help me where is the problem in my code?
I am trying to get access in the database and authentication the user in my bank.
Thanks for your time
I am trying to run below code on netbeans but it is throwing this error "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 '?, esalary=?, eage=?, egender=?, edept=? where eid = ?' at line 1".
please help me with the error
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
//open connection
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false","root","BakerStreet#221b");
//mysql query to update
String sql = "update emp set ename=?, esalary=?, eage=?, egender=?, edept=? where eid = ?";
PreparedStatement ptsmt = con.prepareStatement(sql);
ptsmt.executeUpdate(sql);
ptsmt.setString(1,empName.getText());
ptsmt.setInt(2,Integer.parseInt(empSal.getText()));
ptsmt.setInt(3,Integer.parseInt(empAge.getText()));
ptsmt.setString(4,empGen.getText());
ptsmt.setString(5,empDep.getText());
ptsmt.setInt(6,Integer.parseInt(id.getText()));
ptsmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Record updated Successfully");
con.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
you have called twice executeUpdate(sql) so remove one
you have called executeUpdate(sql) before adding value to parameters so do this :
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
//open connection
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false","root","BakerStreet#221b");
//mysql query to update
String sql = "update emp set ename=?, esalary=?, eage=?, egender=?, edept=? where eid = ?";
PreparedStatement ptsmt = con.prepareStatement(sql);
ptsmt.setString(1,empName.getText());
ptsmt.setInt(2,Integer.parseInt(empSal.getText()));
ptsmt.setInt(3,Integer.parseInt(empAge.getText()));
ptsmt.setString(4,empGen.getText());
ptsmt.setString(5,empDep.getText());
ptsmt.setInt(6,Integer.parseInt(id.getText()));
//execute update ...
ptsmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Record updated Successfully");
con.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
when i run the file, it accepts the query and says update success but when i check my database why does it not update?
private void btnUpdateDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(radioUpdate.isSelected()){
try{
Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/soften?zeroDateTimeBehavior=convertToNull","root","");
st=cn.createStatement();
String sql="UPDATE `tblproductssales` SET "
+" product = ?,quantity = ?"
+" WHERE 'sale no' = ?";
PreparedStatement pst = cn.prepareStatement(sql);
pst.setString(1,editProduct.getText());
pst.setString(2,editQty.getText());
pst.setString(3,editSaleID.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"success update");
//**when i run the file this JOPtionpPane shows
}catch(Exception e){e.printStackTrace();}
}
}
here is my database, the table name is tblproductssales
I am trying to connect to a MySQL database from a jsp page using jdbc in the backend.
I have the following code:
public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
Connection con = null;
if (del.length() == 0) {
del="no data";
}
name = name.replaceAll("\\(.+?\\)", "");
name = name.replaceAll(" ", "_");
del = del.replaceAll(" ", "_");
System.out.println("del "+del);
String url = "jdbc:mysql://localhost:3306/test";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,"root","");
con.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS aiportdetails(code VARCHAR(50) PRIMARY KEY, " +
"name VARCHAR(250), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50))");
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
I am getting the following error at
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
error:
Table 'test.airportdetails' doesn't exist
But from my phpmyadmin I can see that the table is created and exists:
What is the reason I am getting this error?
Thank you.
executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Currently you are trying to use this for creating a table. That's the reason why you are getting that error.
Refer to the documentation Java 6 OR Java 1.4.2 for executeUpdate
EDIT:
You should create a table using Statement
Statement st = con.createStatement();
String table = "Create table .......";
st.executeUpdate(table);
you can put the initialize the connection and load driver at the constructor level, then in the method you can first createt check the table if it exists or create it then if it is successful, continue with the insert operation.like this:
public class MyBean{
String url = "jdbc:mysql://localhost:3306/test,"root","" ";
public MyBean(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url);
}catch(Exception e){
}
}
public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
Connection con = null;
if (del.length() == 0) {
del="no data";
}
name = name.replaceAll("\\(.+?\\)", "");
name = name.replaceAll(" ", "_");
del = del.replaceAll(" ", "_");
System.out.println("del "+del);
try {
con = DriverManager.getConnection(url);
Int result = con.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS aiportdetails(code VARCHAR(50) PRIMARY KEY, " +
"name VARCHAR(250), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50))");
if(result>0){
try{
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
}catch(Exception e){
}finally{
}
}//end if
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
I'm using Tomcat 7, MySql Workbench 5.2.27, JSF 2.0 and this exception comes from the ManagedBean(TripTableBean.java) of my web page(Trip Record.xhtml). It comes up whenever I click to go to Trip Record.xhtml after navigating through my other web pages. Pardon my horrible codes...
TripTableBean.java
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at Database.DBController.readRequest(DBController.java:21)
at Database.TripTableBean.retrieve(TripTableBean.java:389)
at Database.TripTableBean.<init>(TripTableBean.java:69)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
at org.apache.el.parser.AstValue.getTarget(AstValue.java:94)
at org.apache.el.parser.AstValue.getType(AstValue.java:82)
at org.apache.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:176)
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
at org.primefaces.component.datatable.DataTable.isLazy(DataTable.java:904)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:177)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:103)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The method where the exception originates : (TripTableBean.java:389) points to rs2 = db.readRequest(dbQuery2);
public void retrieve() throws SQLException, NamingException {
t = new ArrayList<TripSearchy>();
ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
DBController db = new DBController();
db.setUp();
//SQL: change select statement here
String dbQuery = "select * from (trip inner join agency on trip.id=agency.trip_id inner join tourguide on trip.id=tourguide.trip_id inner join accommodation on trip.id=accommodation.trip_id)";
rs = db.readRequest(dbQuery);
try{
while(rs.next()){
//add to list
id = rs.getInt("trip.id");
name = rs.getString("trip.name");
startDate = rs.getString("trip.startDate");
endDate = rs.getString("trip.endDate");
costOfTrip = rs.getString("trip.costOfTrip");
maxNoOfParticipants = rs.getString("trip.maxNoOfParticipants");
closingDateOfApplication = rs.getString("trip.closingDateOfApplication");
instructions = rs.getString("trip.instructions");
psea = rs.getString("trip.psea");
fasop = rs.getString("trip.fasop");
ktpiop = rs.getString("trip.ktpiop");
opId = rs.getInt("trip.overseasprogramme_id");
overseasProgramme = rs.getString("trip.overseasProgrammeName");
tourGuideName = rs.getString("tourguide.name");
tourGuideContact = rs.getString("tourguide.contact");
companyName = rs.getString("agency.companyName");
agentName = rs.getString("agency.agentName");
agentContact = rs.getString("agency.agentContact");
airlineChoice = rs.getString("agency.airlineChoice");
placeOfLodging = rs.getString("accommodation.placeOfLodging");
startDateOfLodging = rs.getString("accommodation.startDate");
endDateOfLodging = rs.getString("accommodation.endDate");
String dbQuery2 = "Select * from tripstaff where trip_id = '" + id + "'";
rs2 = db.readRequest(dbQuery2);
String lec;
ArrayList<String> dbQueryM = new ArrayList<String>();
while (rs2.next()){
lec = rs2.getString("tripstaff.lecturer_id");
dbQueryM.add("Select * from lecturer where id = '" + lec + "'");
}
ArrayList<NypStaff> nsf = new ArrayList<NypStaff>();
for (int i = 0; i < dbQueryM.size(); i++){
rs3 = db.readRequest(dbQueryM.get(i));
if (rs3.next()){
NypStaff temp = new NypStaff();
//set values retrieved from database into attributes
temp.setName(rs3.getString("lecturer.name"));
temp.setEmail(rs3.getString("lecturer.email"));
temp.setContact(rs3.getString("lecturer.contact"));
nsf.add(temp);
}
}
try {
Calendar c = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Calendar c3 = Calendar.getInstance();
Calendar c4 = Calendar.getInstance();
Calendar c5 = Calendar.getInstance();
try {
c.setTime(formatter.parse(startDate));
c2.setTime(formatter.parse(endDate));
c3.setTime(formatter.parse(startDateOfLodging));
c4.setTime(formatter.parse(endDateOfLodging));
c5.setTime(formatter.parse(closingDateOfApplication));
}
catch (ParseException e1) {
e1.printStackTrace();
}
c.add(Calendar.DATE, 1);
c2.add(Calendar.DATE, 1);
c3.add(Calendar.DATE, 1);
c4.add(Calendar.DATE, 1);
c5.add(Calendar.DATE, 1);
startDate = formatter.format(c.getTime());
endDate = formatter.format(c2.getTime());
startDateOfLodging = formatter.format(c3.getTime());
endDateOfLodging = formatter.format(c4.getTime());
closingDateOfApplication = formatter.format(c5.getTime());
startDated = formatter.parse(startDate);
endDated = formatter.parse(endDate);
startDatedOfLodging = formatter.parse(startDateOfLodging);
endDatedOfLodging = formatter.parse(endDateOfLodging);
closingDatedOfApplication = formatter.parse(closingDateOfApplication);
c.add(Calendar.DATE, -1);
c2.add(Calendar.DATE, -1);
c3.add(Calendar.DATE, -1);
c4.add(Calendar.DATE, -1);
c5.add(Calendar.DATE, -1);
startDate = formatter.format(c.getTime());
endDate = formatter.format(c2.getTime());
startDateOfLodging = formatter.format(c3.getTime());
endDateOfLodging = formatter.format(c4.getTime());
closingDateOfApplication = formatter.format(c5.getTime());
}
catch (ParseException e1) {
e1.printStackTrace();
}
t.add(new TripSearchy (id, opId, overseasProgramme, name, startDated, startDate, endDated, endDate, costOfTrip, ns, nsf, staffName, tourGuideName, tourGuideContact, companyName, agentName, agentContact, airlineChoice, placeOfLodging, startDatedOfLodging, startDateOfLodging, endDatedOfLodging, endDateOfLodging, maxNoOfParticipants, closingDatedOfApplication, closingDateOfApplication, instructions, psea, fasop, ktpiop));
}
}catch (Exception e) {
e.printStackTrace();
}
db.terminate();
}
It seems that I have exhausted my connection =\ May I know how do I reduce my usage of the connection/increase the capacity of the connection?
Update:
DBController.java
public class DBController {
private DataSource ds;
Connection con;
public void setUp() throws NamingException{
//connect to database
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/it2299");
}
public ResultSet readRequest(String dbQuery){
ResultSet rs=null;
try{
con = ds.getConnection();
Statement stmt = con.createStatement();
rs = stmt.executeQuery(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return rs;
}
public int updateRequest(String dbQuery){
int count=0;
try{
con = ds.getConnection();
Statement stmt = con.createStatement();
count=stmt.executeUpdate(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return count;
}
public void terminate(){
try {con.close();}
catch(Exception e){e.printStackTrace();}
}
}
Update 2:
This exception occurs when the scope of my ManagedBean(TripTableBean.java) is ViewScoped, it doesn't occur when I change it to SessionScoped. However if it is SessionScoped, I'll need to find a way to kill session and recreate a new session whenever I come to this web page if not my dataTable on this page won't load updated changes from the database.
As you hinted yourself, your code is horrible. You need to ensure that all JDBC resources are acquired and closed in the shortest possibe scope in a try-finally block. Rewrite your code so that it follows the following standard JDBC idiom:
public List<Entity> list() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Entity> entities = new ArrayList<Entity>();
try {
connection = Database.getConnection();
statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setFoo(resultSet.getString("foo"));
entity.setBar(resultSet.getString("bar"));
entities.add(entity);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return entities;
}
See also:
If I use a singleton class for a database connection, can one user close the connection for everybody?
JDBC MySql connection pooling practices to avoid exhausted connection pool
what are you connection pool settings can you post whats in DBController?
Tip: db.terminate() should be in finally{} block, may be you are lossing connections on exceptions.
Update:
Posting some of the modifications that might help you, but DO CLEAN UP THE CODE for maintenance sake. Look for comments where changes have been made.
public class DBController {
private DataSource ds;
private Connection con;// NEW CHANGE
public void setUp() throws NamingException{
//connect to database
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/it2299");
con = ds.getConnection(); // NEW CHANGE
}
public ResultSet readRequest(String dbQuery){
ResultSet rs=null;
try{
//REMOVED CODE FROM HERE
Statement stmt = con.createStatement();
rs = stmt.executeQuery(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return rs;
}
public int updateRequest(String dbQuery){
int count=0;
try{
//REMOVED CODE FROM HERE
Statement stmt = con.createStatement();
count=stmt.executeUpdate(dbQuery);
}
catch(Exception e){e.printStackTrace();}
return count;
}
public void terminate(){
try {con.close();}
catch(Exception e){e.printStackTrace();}
}
}
Code cannot be improved beyond this by me, but I suggest have a look at some of the best practices over net and as suggested by #BalusC.
Remember: To close the connection object when done.