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
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
New contributor
|
show 2 more comments
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
New contributor
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
|
show 2 more comments
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
New contributor
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
java jdbc garbage-collection apache-commons-dbcp
New contributor
New contributor
New contributor
asked yesterday
Onkar MusaleOnkar Musale
165
165
New contributor
New contributor
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
|
show 2 more comments
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
|
show 2 more comments
2 Answers
2
active
oldest
votes
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.
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 usingtry(…)
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
add a comment |
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.
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 havestatic 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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
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 usingtry(…)
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
add a comment |
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.
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 usingtry(…)
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
add a comment |
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.
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.
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 usingtry(…)
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
add a comment |
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 usingtry(…)
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
add a comment |
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.
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 havestatic 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
add a comment |
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.
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 havestatic 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
add a comment |
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.
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.
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 havestatic 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
add a comment |
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 havestatic 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
add a comment |
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.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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