Is it ok to use same BasicDataSource, Connection, Statement and ResultSet Object in multiple class methods.?2019 Community Moderator ElectionMust JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?Java Servlet DB Query with Ajax - slow query time and querystring not always fully passed to the servletunable to drop table in HSQLDBjdbc get generatedKeys along with other data efficieintlySlow sql execution under Oracle connection from Weblogic controlled data sourceWhy reading byte array to an Object throws java.io.StreamCorruptedException?MySQL Query result is very slowOverriding private methods in (non-)static classessorting a JTable using getColumnClass() when connected to JDBCget COLUMN_NAME and TABLESPACE_NAME in one query

A bug in Excel? Conditional formatting for marking duplicates also highlights unique value

Do natural melee weapons (from racial traits) trigger Improved Divine Smite?

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

Affine transformation of circular arc in 3D

What is a term for a function that when called repeatedly, has the same effect as calling once?

Why do phishing e-mails use faked e-mail addresses instead of the real one?

Is it a Cyclops number? "Nobody" knows!

The past tense for the quoting particle って

“I had a flat in the centre of town, but I didn’t like living there, so …”

When to use the term transposed instead of modulation?

What is better: yes / no radio, or simple checkbox?

Was it really inappropriate to write a pull request for the company I interviewed with?

Should I use HTTPS on a domain that will only be used for redirection?

Convert an array of objects to array of the objects' values

What is Tony Stark injecting into himself in Iron Man 3?

Why are special aircraft used for the carriers in the United States Navy?

Did Amazon pay $0 in taxes last year?

Different Account page layouts, what are they?

How spaceships determine each other's mass in space?

Create chunks from an array

What does "rhumatis" mean?

New invention compresses matter to produce energy? or other items? (Short Story)

How do we objectively assess if a dialogue sounds unnatural or cringy?

What can I do if someone tampers with my SSH public key?



Is it ok to use same BasicDataSource, Connection, Statement and ResultSet Object in multiple class methods.?



2019 Community Moderator ElectionMust JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?Java Servlet DB Query with Ajax - slow query time and querystring not always fully passed to the servletunable to drop table in HSQLDBjdbc get generatedKeys along with other data efficieintlySlow sql execution under Oracle connection from Weblogic controlled data sourceWhy reading byte array to an Object throws java.io.StreamCorruptedException?MySQL Query result is very slowOverriding private methods in (non-)static classessorting a JTable using getColumnClass() when connected to JDBCget COLUMN_NAME and TABLESPACE_NAME in one query










0















I have below code which uses static objects of BasicDataSource, Sql Connection, Statement and ResultSet. The code below is working fine, but i just want to know about the safety of using these kinds of coding practices. or how can i optimize the below code so that it can become more stable and can reliable.



public class Testing 
static BasicDataSource bds = DBConnection.getInstance().getBds();
static Connection con = null;
static PreparedStatement stmt = null;
static ResultSet rs = null;

private void show()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM users");
rs = stmt.executeQuery();
if(rs.next())
System.out.println(rs.getString("firstname") + " " + rs.getString("lastname"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void display()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM agent_cities");
rs = stmt.executeQuery();
while(rs.next())
System.out.println(rs.getString("city_name"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void add()
try
con = bds.getConnection();
stmt = con.prepareStatement("UPDATE users SET firstname = 'shsh' WHERE id = 2");
stmt.executeUpdate();
System.out.println("updated successfully");
catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



public static void main(String[] args)
Testing t = new Testing();
t.show();
t.display();
t.add();




Thanks in advance.
Do share your cases on which you can break above code and question about its safety.










share|improve this question







New contributor




Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Depending on the complexity of an application, you really should not be using fields for connections, statements and result sets (and static fields are even a bigger smell).

    – Mark Rotteveel
    yesterday











  • Then what are better alternatives.

    – Onkar Musale
    22 hours ago











  • Local variables of course.

    – Mark Rotteveel
    21 hours ago











  • and waht's the reason for that

    – Onkar Musale
    19 hours ago











  • It prevents connection from living too long, it prevents inadvertent sharing of connections between multiple threads, and it prevents other types of resource leaks.

    – Mark Rotteveel
    19 hours ago















0















I have below code which uses static objects of BasicDataSource, Sql Connection, Statement and ResultSet. The code below is working fine, but i just want to know about the safety of using these kinds of coding practices. or how can i optimize the below code so that it can become more stable and can reliable.



public class Testing 
static BasicDataSource bds = DBConnection.getInstance().getBds();
static Connection con = null;
static PreparedStatement stmt = null;
static ResultSet rs = null;

private void show()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM users");
rs = stmt.executeQuery();
if(rs.next())
System.out.println(rs.getString("firstname") + " " + rs.getString("lastname"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void display()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM agent_cities");
rs = stmt.executeQuery();
while(rs.next())
System.out.println(rs.getString("city_name"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void add()
try
con = bds.getConnection();
stmt = con.prepareStatement("UPDATE users SET firstname = 'shsh' WHERE id = 2");
stmt.executeUpdate();
System.out.println("updated successfully");
catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



public static void main(String[] args)
Testing t = new Testing();
t.show();
t.display();
t.add();




Thanks in advance.
Do share your cases on which you can break above code and question about its safety.










share|improve this question







New contributor




Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Depending on the complexity of an application, you really should not be using fields for connections, statements and result sets (and static fields are even a bigger smell).

    – Mark Rotteveel
    yesterday











  • Then what are better alternatives.

    – Onkar Musale
    22 hours ago











  • Local variables of course.

    – Mark Rotteveel
    21 hours ago











  • and waht's the reason for that

    – Onkar Musale
    19 hours ago











  • It prevents connection from living too long, it prevents inadvertent sharing of connections between multiple threads, and it prevents other types of resource leaks.

    – Mark Rotteveel
    19 hours ago













0












0








0


0






I have below code which uses static objects of BasicDataSource, Sql Connection, Statement and ResultSet. The code below is working fine, but i just want to know about the safety of using these kinds of coding practices. or how can i optimize the below code so that it can become more stable and can reliable.



public class Testing 
static BasicDataSource bds = DBConnection.getInstance().getBds();
static Connection con = null;
static PreparedStatement stmt = null;
static ResultSet rs = null;

private void show()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM users");
rs = stmt.executeQuery();
if(rs.next())
System.out.println(rs.getString("firstname") + " " + rs.getString("lastname"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void display()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM agent_cities");
rs = stmt.executeQuery();
while(rs.next())
System.out.println(rs.getString("city_name"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void add()
try
con = bds.getConnection();
stmt = con.prepareStatement("UPDATE users SET firstname = 'shsh' WHERE id = 2");
stmt.executeUpdate();
System.out.println("updated successfully");
catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



public static void main(String[] args)
Testing t = new Testing();
t.show();
t.display();
t.add();




Thanks in advance.
Do share your cases on which you can break above code and question about its safety.










share|improve this question







New contributor




Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I have below code which uses static objects of BasicDataSource, Sql Connection, Statement and ResultSet. The code below is working fine, but i just want to know about the safety of using these kinds of coding practices. or how can i optimize the below code so that it can become more stable and can reliable.



public class Testing 
static BasicDataSource bds = DBConnection.getInstance().getBds();
static Connection con = null;
static PreparedStatement stmt = null;
static ResultSet rs = null;

private void show()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM users");
rs = stmt.executeQuery();
if(rs.next())
System.out.println(rs.getString("firstname") + " " + rs.getString("lastname"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void display()
try
con = bds.getConnection();
stmt = con.prepareStatement("SELECT * FROM agent_cities");
rs = stmt.executeQuery();
while(rs.next())
System.out.println(rs.getString("city_name"));

catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



private void add()
try
con = bds.getConnection();
stmt = con.prepareStatement("UPDATE users SET firstname = 'shsh' WHERE id = 2");
stmt.executeUpdate();
System.out.println("updated successfully");
catch (SQLException e)
e.printStackTrace();
finally
try
con.close();
catch (SQLException e)
e.printStackTrace();



public static void main(String[] args)
Testing t = new Testing();
t.show();
t.display();
t.add();




Thanks in advance.
Do share your cases on which you can break above code and question about its safety.







java jdbc garbage-collection apache-commons-dbcp






share|improve this question







New contributor




Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









Onkar MusaleOnkar Musale

165




165




New contributor




Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Onkar Musale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • Depending on the complexity of an application, you really should not be using fields for connections, statements and result sets (and static fields are even a bigger smell).

    – Mark Rotteveel
    yesterday











  • Then what are better alternatives.

    – Onkar Musale
    22 hours ago











  • Local variables of course.

    – Mark Rotteveel
    21 hours ago











  • and waht's the reason for that

    – Onkar Musale
    19 hours ago











  • It prevents connection from living too long, it prevents inadvertent sharing of connections between multiple threads, and it prevents other types of resource leaks.

    – Mark Rotteveel
    19 hours ago

















  • Depending on the complexity of an application, you really should not be using fields for connections, statements and result sets (and static fields are even a bigger smell).

    – Mark Rotteveel
    yesterday











  • Then what are better alternatives.

    – Onkar Musale
    22 hours ago











  • Local variables of course.

    – Mark Rotteveel
    21 hours ago











  • and waht's the reason for that

    – Onkar Musale
    19 hours ago











  • It prevents connection from living too long, it prevents inadvertent sharing of connections between multiple threads, and it prevents other types of resource leaks.

    – Mark Rotteveel
    19 hours ago
















Depending on the complexity of an application, you really should not be using fields for connections, statements and result sets (and static fields are even a bigger smell).

– Mark Rotteveel
yesterday





Depending on the complexity of an application, you really should not be using fields for connections, statements and result sets (and static fields are even a bigger smell).

– Mark Rotteveel
yesterday













Then what are better alternatives.

– Onkar Musale
22 hours ago





Then what are better alternatives.

– Onkar Musale
22 hours ago













Local variables of course.

– Mark Rotteveel
21 hours ago





Local variables of course.

– Mark Rotteveel
21 hours ago













and waht's the reason for that

– Onkar Musale
19 hours ago





and waht's the reason for that

– Onkar Musale
19 hours ago













It prevents connection from living too long, it prevents inadvertent sharing of connections between multiple threads, and it prevents other types of resource leaks.

– Mark Rotteveel
19 hours ago





It prevents connection from living too long, it prevents inadvertent sharing of connections between multiple threads, and it prevents other types of resource leaks.

– Mark Rotteveel
19 hours ago












2 Answers
2






active

oldest

votes


















1














Better use try-with-resources. This automatically closes Connection, Statement and ResultSet, even when an exception was raised, or on an inner return.



 String sql = "UPDATE users SET firstname = ? WHERE id = ?";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
stmt.setString(1, "shsh");
stmt.setLong(2, 2);
stmt.executeUpdate();
System.out.println("updated successfully");


String sql = "SELECT city_name FROM agent_cities";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
try (ResultSet rs = stmt.executeQuery())
while(rs.next())
System.out.println(rs.getString("city_name"));





This is better for garbage collection. Prevents unnice rs2, rs3. Allows multi-user concurrency, like in a server application. Calls that query themselves.
And static is even more in the style of global variables.






share|improve this answer























  • This is not about garbage collection but resource cleanup whereas “resource” means any resource not managed by Java’s garbage collector. The memory of these objects in the Java heap is only a minor issue.

    – Holger
    yesterday











  • @Holger true, thanks. In fact I am a bit lost of finding the correct words here. An old style C / Fortran programmer would use global variables as proposed.

    – Joop Eggen
    yesterday






  • 1





    The wording is tricky, as with other programming languages, anything that needs allocation and deallocation is a “resource”, which includes explicitly managed memory. The mind job of a Java programmer is to exclude the managed heap memory from the set of resources, while considering “resource” as something that still needs explicit closing (considering using try(…) as explicit management) and should be closed as early as possible. Then, it gets easier to understand the futility of the old idea of closing resources in a finalizer, as the garbage collector only cares for heap memory.

    – Holger
    yesterday











  • Thanks. from now i will use above try-with-resources block.

    – Onkar Musale
    22 hours ago



















1














It is more or less ok if we are talking about such a small program.
But there is no need to keep con, stmt and rs as a static variables, they can be declared inside a method. Also, you need to rewrite try catch finally blocks and close resources properly:



Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
// your code
catch (SQLException e)
e.printStackTrace();
finally
try if (rs != null) rs.close(); catch (Exception e) e.printStackTrace();
try if (stmt != null) stmt.close(); catch (Exception e) e.printStackTrace();
try if (conn != null) conn.close(); catch (Exception e) e.printStackTrace();



As a next step you can check try-with-resources construction to clean up this code.






share|improve this answer























  • Yeah. but i have much large program where i can't create new objects for each method signature so what is your solution for very large program containing many method signatures.

    – Onkar Musale
    yesterday












  • i will check try-with-resources. thanks

    – Onkar Musale
    yesterday











  • It depends on the tech stack. If you have java without spring/hibernate, then you need a single data source (which you already have static BasicDataSource bds = DBConnection.getInstance().getBds();) and close resources properly.

    – Mykhailo Hodovaniuk
    yesterday












  • yup i am not using spring/hibernate. i am using Java Servlets and Maven as a build tool with Eclipse IDE.

    – Onkar Musale
    yesterday










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






Onkar Musale is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023282%2fis-it-ok-to-use-same-basicdatasource-connection-statement-and-resultset-object%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Better use try-with-resources. This automatically closes Connection, Statement and ResultSet, even when an exception was raised, or on an inner return.



 String sql = "UPDATE users SET firstname = ? WHERE id = ?";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
stmt.setString(1, "shsh");
stmt.setLong(2, 2);
stmt.executeUpdate();
System.out.println("updated successfully");


String sql = "SELECT city_name FROM agent_cities";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
try (ResultSet rs = stmt.executeQuery())
while(rs.next())
System.out.println(rs.getString("city_name"));





This is better for garbage collection. Prevents unnice rs2, rs3. Allows multi-user concurrency, like in a server application. Calls that query themselves.
And static is even more in the style of global variables.






share|improve this answer























  • This is not about garbage collection but resource cleanup whereas “resource” means any resource not managed by Java’s garbage collector. The memory of these objects in the Java heap is only a minor issue.

    – Holger
    yesterday











  • @Holger true, thanks. In fact I am a bit lost of finding the correct words here. An old style C / Fortran programmer would use global variables as proposed.

    – Joop Eggen
    yesterday






  • 1





    The wording is tricky, as with other programming languages, anything that needs allocation and deallocation is a “resource”, which includes explicitly managed memory. The mind job of a Java programmer is to exclude the managed heap memory from the set of resources, while considering “resource” as something that still needs explicit closing (considering using try(…) as explicit management) and should be closed as early as possible. Then, it gets easier to understand the futility of the old idea of closing resources in a finalizer, as the garbage collector only cares for heap memory.

    – Holger
    yesterday











  • Thanks. from now i will use above try-with-resources block.

    – Onkar Musale
    22 hours ago
















1














Better use try-with-resources. This automatically closes Connection, Statement and ResultSet, even when an exception was raised, or on an inner return.



 String sql = "UPDATE users SET firstname = ? WHERE id = ?";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
stmt.setString(1, "shsh");
stmt.setLong(2, 2);
stmt.executeUpdate();
System.out.println("updated successfully");


String sql = "SELECT city_name FROM agent_cities";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
try (ResultSet rs = stmt.executeQuery())
while(rs.next())
System.out.println(rs.getString("city_name"));





This is better for garbage collection. Prevents unnice rs2, rs3. Allows multi-user concurrency, like in a server application. Calls that query themselves.
And static is even more in the style of global variables.






share|improve this answer























  • This is not about garbage collection but resource cleanup whereas “resource” means any resource not managed by Java’s garbage collector. The memory of these objects in the Java heap is only a minor issue.

    – Holger
    yesterday











  • @Holger true, thanks. In fact I am a bit lost of finding the correct words here. An old style C / Fortran programmer would use global variables as proposed.

    – Joop Eggen
    yesterday






  • 1





    The wording is tricky, as with other programming languages, anything that needs allocation and deallocation is a “resource”, which includes explicitly managed memory. The mind job of a Java programmer is to exclude the managed heap memory from the set of resources, while considering “resource” as something that still needs explicit closing (considering using try(…) as explicit management) and should be closed as early as possible. Then, it gets easier to understand the futility of the old idea of closing resources in a finalizer, as the garbage collector only cares for heap memory.

    – Holger
    yesterday











  • Thanks. from now i will use above try-with-resources block.

    – Onkar Musale
    22 hours ago














1












1








1







Better use try-with-resources. This automatically closes Connection, Statement and ResultSet, even when an exception was raised, or on an inner return.



 String sql = "UPDATE users SET firstname = ? WHERE id = ?";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
stmt.setString(1, "shsh");
stmt.setLong(2, 2);
stmt.executeUpdate();
System.out.println("updated successfully");


String sql = "SELECT city_name FROM agent_cities";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
try (ResultSet rs = stmt.executeQuery())
while(rs.next())
System.out.println(rs.getString("city_name"));





This is better for garbage collection. Prevents unnice rs2, rs3. Allows multi-user concurrency, like in a server application. Calls that query themselves.
And static is even more in the style of global variables.






share|improve this answer













Better use try-with-resources. This automatically closes Connection, Statement and ResultSet, even when an exception was raised, or on an inner return.



 String sql = "UPDATE users SET firstname = ? WHERE id = ?";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
stmt.setString(1, "shsh");
stmt.setLong(2, 2);
stmt.executeUpdate();
System.out.println("updated successfully");


String sql = "SELECT city_name FROM agent_cities";
try (Connection con = bds.getConnection();
PreparedStatement stmt = con.prepareStatement())
try (ResultSet rs = stmt.executeQuery())
while(rs.next())
System.out.println(rs.getString("city_name"));





This is better for garbage collection. Prevents unnice rs2, rs3. Allows multi-user concurrency, like in a server application. Calls that query themselves.
And static is even more in the style of global variables.







share|improve this answer












share|improve this answer



share|improve this answer










answered yesterday









Joop EggenJoop Eggen

77.9k755103




77.9k755103












  • This is not about garbage collection but resource cleanup whereas “resource” means any resource not managed by Java’s garbage collector. The memory of these objects in the Java heap is only a minor issue.

    – Holger
    yesterday











  • @Holger true, thanks. In fact I am a bit lost of finding the correct words here. An old style C / Fortran programmer would use global variables as proposed.

    – Joop Eggen
    yesterday






  • 1





    The wording is tricky, as with other programming languages, anything that needs allocation and deallocation is a “resource”, which includes explicitly managed memory. The mind job of a Java programmer is to exclude the managed heap memory from the set of resources, while considering “resource” as something that still needs explicit closing (considering using try(…) as explicit management) and should be closed as early as possible. Then, it gets easier to understand the futility of the old idea of closing resources in a finalizer, as the garbage collector only cares for heap memory.

    – Holger
    yesterday











  • Thanks. from now i will use above try-with-resources block.

    – Onkar Musale
    22 hours ago


















  • This is not about garbage collection but resource cleanup whereas “resource” means any resource not managed by Java’s garbage collector. The memory of these objects in the Java heap is only a minor issue.

    – Holger
    yesterday











  • @Holger true, thanks. In fact I am a bit lost of finding the correct words here. An old style C / Fortran programmer would use global variables as proposed.

    – Joop Eggen
    yesterday






  • 1





    The wording is tricky, as with other programming languages, anything that needs allocation and deallocation is a “resource”, which includes explicitly managed memory. The mind job of a Java programmer is to exclude the managed heap memory from the set of resources, while considering “resource” as something that still needs explicit closing (considering using try(…) as explicit management) and should be closed as early as possible. Then, it gets easier to understand the futility of the old idea of closing resources in a finalizer, as the garbage collector only cares for heap memory.

    – Holger
    yesterday











  • Thanks. from now i will use above try-with-resources block.

    – Onkar Musale
    22 hours ago

















This is not about garbage collection but resource cleanup whereas “resource” means any resource not managed by Java’s garbage collector. The memory of these objects in the Java heap is only a minor issue.

– Holger
yesterday





This is not about garbage collection but resource cleanup whereas “resource” means any resource not managed by Java’s garbage collector. The memory of these objects in the Java heap is only a minor issue.

– Holger
yesterday













@Holger true, thanks. In fact I am a bit lost of finding the correct words here. An old style C / Fortran programmer would use global variables as proposed.

– Joop Eggen
yesterday





@Holger true, thanks. In fact I am a bit lost of finding the correct words here. An old style C / Fortran programmer would use global variables as proposed.

– Joop Eggen
yesterday




1




1





The wording is tricky, as with other programming languages, anything that needs allocation and deallocation is a “resource”, which includes explicitly managed memory. The mind job of a Java programmer is to exclude the managed heap memory from the set of resources, while considering “resource” as something that still needs explicit closing (considering using try(…) as explicit management) and should be closed as early as possible. Then, it gets easier to understand the futility of the old idea of closing resources in a finalizer, as the garbage collector only cares for heap memory.

– Holger
yesterday





The wording is tricky, as with other programming languages, anything that needs allocation and deallocation is a “resource”, which includes explicitly managed memory. The mind job of a Java programmer is to exclude the managed heap memory from the set of resources, while considering “resource” as something that still needs explicit closing (considering using try(…) as explicit management) and should be closed as early as possible. Then, it gets easier to understand the futility of the old idea of closing resources in a finalizer, as the garbage collector only cares for heap memory.

– Holger
yesterday













Thanks. from now i will use above try-with-resources block.

– Onkar Musale
22 hours ago






Thanks. from now i will use above try-with-resources block.

– Onkar Musale
22 hours ago














1














It is more or less ok if we are talking about such a small program.
But there is no need to keep con, stmt and rs as a static variables, they can be declared inside a method. Also, you need to rewrite try catch finally blocks and close resources properly:



Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
// your code
catch (SQLException e)
e.printStackTrace();
finally
try if (rs != null) rs.close(); catch (Exception e) e.printStackTrace();
try if (stmt != null) stmt.close(); catch (Exception e) e.printStackTrace();
try if (conn != null) conn.close(); catch (Exception e) e.printStackTrace();



As a next step you can check try-with-resources construction to clean up this code.






share|improve this answer























  • Yeah. but i have much large program where i can't create new objects for each method signature so what is your solution for very large program containing many method signatures.

    – Onkar Musale
    yesterday












  • i will check try-with-resources. thanks

    – Onkar Musale
    yesterday











  • It depends on the tech stack. If you have java without spring/hibernate, then you need a single data source (which you already have static BasicDataSource bds = DBConnection.getInstance().getBds();) and close resources properly.

    – Mykhailo Hodovaniuk
    yesterday












  • yup i am not using spring/hibernate. i am using Java Servlets and Maven as a build tool with Eclipse IDE.

    – Onkar Musale
    yesterday















1














It is more or less ok if we are talking about such a small program.
But there is no need to keep con, stmt and rs as a static variables, they can be declared inside a method. Also, you need to rewrite try catch finally blocks and close resources properly:



Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
// your code
catch (SQLException e)
e.printStackTrace();
finally
try if (rs != null) rs.close(); catch (Exception e) e.printStackTrace();
try if (stmt != null) stmt.close(); catch (Exception e) e.printStackTrace();
try if (conn != null) conn.close(); catch (Exception e) e.printStackTrace();



As a next step you can check try-with-resources construction to clean up this code.






share|improve this answer























  • Yeah. but i have much large program where i can't create new objects for each method signature so what is your solution for very large program containing many method signatures.

    – Onkar Musale
    yesterday












  • i will check try-with-resources. thanks

    – Onkar Musale
    yesterday











  • It depends on the tech stack. If you have java without spring/hibernate, then you need a single data source (which you already have static BasicDataSource bds = DBConnection.getInstance().getBds();) and close resources properly.

    – Mykhailo Hodovaniuk
    yesterday












  • yup i am not using spring/hibernate. i am using Java Servlets and Maven as a build tool with Eclipse IDE.

    – Onkar Musale
    yesterday













1












1








1







It is more or less ok if we are talking about such a small program.
But there is no need to keep con, stmt and rs as a static variables, they can be declared inside a method. Also, you need to rewrite try catch finally blocks and close resources properly:



Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
// your code
catch (SQLException e)
e.printStackTrace();
finally
try if (rs != null) rs.close(); catch (Exception e) e.printStackTrace();
try if (stmt != null) stmt.close(); catch (Exception e) e.printStackTrace();
try if (conn != null) conn.close(); catch (Exception e) e.printStackTrace();



As a next step you can check try-with-resources construction to clean up this code.






share|improve this answer













It is more or less ok if we are talking about such a small program.
But there is no need to keep con, stmt and rs as a static variables, they can be declared inside a method. Also, you need to rewrite try catch finally blocks and close resources properly:



Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
// your code
catch (SQLException e)
e.printStackTrace();
finally
try if (rs != null) rs.close(); catch (Exception e) e.printStackTrace();
try if (stmt != null) stmt.close(); catch (Exception e) e.printStackTrace();
try if (conn != null) conn.close(); catch (Exception e) e.printStackTrace();



As a next step you can check try-with-resources construction to clean up this code.







share|improve this answer












share|improve this answer



share|improve this answer










answered yesterday









Mykhailo HodovaniukMykhailo Hodovaniuk

31116




31116












  • Yeah. but i have much large program where i can't create new objects for each method signature so what is your solution for very large program containing many method signatures.

    – Onkar Musale
    yesterday












  • i will check try-with-resources. thanks

    – Onkar Musale
    yesterday











  • It depends on the tech stack. If you have java without spring/hibernate, then you need a single data source (which you already have static BasicDataSource bds = DBConnection.getInstance().getBds();) and close resources properly.

    – Mykhailo Hodovaniuk
    yesterday












  • yup i am not using spring/hibernate. i am using Java Servlets and Maven as a build tool with Eclipse IDE.

    – Onkar Musale
    yesterday

















  • Yeah. but i have much large program where i can't create new objects for each method signature so what is your solution for very large program containing many method signatures.

    – Onkar Musale
    yesterday












  • i will check try-with-resources. thanks

    – Onkar Musale
    yesterday











  • It depends on the tech stack. If you have java without spring/hibernate, then you need a single data source (which you already have static BasicDataSource bds = DBConnection.getInstance().getBds();) and close resources properly.

    – Mykhailo Hodovaniuk
    yesterday












  • yup i am not using spring/hibernate. i am using Java Servlets and Maven as a build tool with Eclipse IDE.

    – Onkar Musale
    yesterday
















Yeah. but i have much large program where i can't create new objects for each method signature so what is your solution for very large program containing many method signatures.

– Onkar Musale
yesterday






Yeah. but i have much large program where i can't create new objects for each method signature so what is your solution for very large program containing many method signatures.

– Onkar Musale
yesterday














i will check try-with-resources. thanks

– Onkar Musale
yesterday





i will check try-with-resources. thanks

– Onkar Musale
yesterday













It depends on the tech stack. If you have java without spring/hibernate, then you need a single data source (which you already have static BasicDataSource bds = DBConnection.getInstance().getBds();) and close resources properly.

– Mykhailo Hodovaniuk
yesterday






It depends on the tech stack. If you have java without spring/hibernate, then you need a single data source (which you already have static BasicDataSource bds = DBConnection.getInstance().getBds();) and close resources properly.

– Mykhailo Hodovaniuk
yesterday














yup i am not using spring/hibernate. i am using Java Servlets and Maven as a build tool with Eclipse IDE.

– Onkar Musale
yesterday





yup i am not using spring/hibernate. i am using Java Servlets and Maven as a build tool with Eclipse IDE.

– Onkar Musale
yesterday










Onkar Musale is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Onkar Musale is a new contributor. Be nice, and check out our Code of Conduct.












Onkar Musale is a new contributor. Be nice, and check out our Code of Conduct.











Onkar Musale is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023282%2fis-it-ok-to-use-same-basicdatasource-connection-statement-and-resultset-object%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page