I am developing a web application using JSP & Servlet (IDE: Eclipse, Database: Oracle10).
I have developed java class which returns a static connection, and that connection will be used by my entire web application.
public class DBConnection
{
private static Connection con = null;
static Connection getConnection(String str)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("MyValuesHere");
System.out.println("New instance of Connection is created for: "+str);
}
catch(ClassNotFoundException cnfe)
{
System.out.println("Error loading class!");
cnfe.printStackTrace();
}
catch(SQLException sqle)
{
System.out.println("Error connecting to the database!");
sqle.printStackTrace();
}
return con;
}//getConnection()
}//class
Above class is working fine. Then I have another 4 java classes for
Inserting
Updating
Deleting
Selecting
data from database using the above connection. So in those 4 classes I am getting connection which is created in my DBConnection class, and those four classes are also working fine. This four classes are used in my all Servlet's.
To get Connection in those 4 classes I am writing following line:
private static Connection con = DBConnection.getConnection("UpdateQuery.java");
But problem is that I want to share the same connection in all four classes, but connection is created separately in those 4 classes. So how should I share the same connection in those four classes? is there better way of doing this? and if I use this approach will there be any issues in web application because of sharing the connection for whole application?
You are (implicitly) trying to solve a non-trivial task.
Such things are normally done by the container - taking connections from a pool, then returning them back, reconnection etc...
If you use a fully functional applications server you'd better configure and use data sources.
If your server doesn't support data sources, do not mess up with saving connection into a private field. What for example happenes when your connection is lost? Your private variable will have a non-working connection. Do you have any recovery mechanism?
Your code will be much more robust if you get it in the beginning of the business operation and then close it.
Or try to find a professionally written library that supports connection pools - it will do pretty much the same as a classic container in handling a connection pool.
Or write it yourself, but it will be a separate task with many questions.
Looks like you wanted to turn Connection into a singleton but then forgot to check whether it's been instantiated already. In getConnection you could check if con is not null in the first place and return that instance right away. Only if con is still null, proceed with initialization.
You should save the created connection instance into a private static field in DBConnection, and when getConnection is called, you check if the field is null, then create the connection, then return it:
if (connection == null) {
connection = createConnection();
}
return connection;
where connection is a private static Connection connection field of DBConnection class.
However I strongly suggest to not use this approach as sharing a connection between concurrent threads will cause serious problems. I suggest to use connection pooling
Related
I am working on a project which need to use jsoup to parse html source. I found it create a new connection every time.
public static Connection connect(String url) {
Connection con = new HttpConnection();
con.url(url);
return con;
}
Is there anyway to use a shared connection just like JDBC connection pool?
In JDBC, all the connections are made to the same database instance so it's logical to group those together and create connection pool (as processes can re-use the connections).
However, in the above example, we are making a connection per url and hence, each connection will be separate and won't be reusable. So, in this case, it makes sense to create a new connection.
I have a bukkit plugin (minecraft) that requires a connection to the database.
Should a database connection stay open all the time, or be opened and closed when needed?
The database connection must be opened only when its needed and closed after doing all the necessary job with it. Code sample:
Prior to Java 7:
Connection con = null;
try {
con = ... //retrieve the database connection
//do your work...
} catch (SQLException e) {
//handle the exception
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException shouldNotHandleMe) {
//...
}
}
Java 7:
try (Connection con = ...) {
} catch (SQLException e) {
}
//no need to call Connection#close since now Connection interface extends Autocloseable
But since manually opening a database connection is too expensive, it is highly recommended to use a database connection pool, represented in Java with DataSource interface. This will handle the physical database connections for you and when you close it (i.e. calling Connection#close), the physical database connection will just be in SLEEP mode and still be open.
Related Q/A:
Java Connection Pooling
Some tools to handle database connection pooling:
BoneCP
c3po
Apache Commons DBCP
HikariCP
Depends on what are your needs.
Creating a connection takes some time, so if you need to access database frequently it's better to keep the connection open. Also it's better to create a pool, so that many users can access database simultaneously(if it's needed).
If you need to use this connection only few times you may not keep it open, but you will have delay when you would like to access database. So i suggest you to make a timer that will keep connection open for some time(connection timeout).
You need to close your connections after each query executions.Sometimes you need to execute multiple queries at the same time because the queries are hanging from each other.Such as "first insert task then assign it to the employees".At this time execute your queries on the same transaction and commit it, if some errors occur then rollback.By default autocommit is disabled in JDBC. Example
Use connection pooling.If you are developing a webapplication then use App Server connection pooling.App server will use the same pooling for each of your applications so you can control the connection count from the one point.Highly recommend the Apache Tomcat Connection pooling.Example
As an additional info:
Connection, Statement and ResultSet.
1.If you close connection you don't need close statement or resultset.Both of them will be closed automatically
2.If you close Statement it will close ResultSet also
3.if you use try-with-resources like this:
try (Connection con = ...) {
} catch (SQLException e) {
}
it will close the connection automatically.Because try-with-resources require autoclosable objects and Connection is autocloseable.You can see the details about try-with-resources here
Actually, it's all matter on how you write your application! It's an art, but sadly everyone takes a tutorial for a good practice like Microsoft's tutorials.
If you know what you are coding, then you keep your connection open for the lifetime of the application. It's simple, not because you have to go at work in the morning that everyday we have to build a special route just for you! You take that single route or 2 or 4 like everyone does! You judge for the traffics and you build 2, 4 or 6 routes as needed. If there is traffic with these 4 or 6 routes, you wait!
Happy coding.
The Connection should be opened only when required. If it is open before the actual need, it reduces one active connection from the connection pool..so it ultimately effects the users of the application.
So,it is always a better practice to open connection only when required and closing it after completion of process.
Always try puttting you connection close logic inside the finally block that will ensure that your connection will be closed,even if any exception occurs in the application
finally
{
connection.close()
}
I'm running a web application on Tomcat. I have a class that handles all DB queries.
This class contains the Connection object and methods that returns query results.
This is the connection object:
private static Connection conn = null;
It has only one instance (singleton).
In addition, I have methods that execute queries, such as search for a user in the db:
public static ResultSet searchUser(String user, String pass) throws SQLException
This method uses the static Connection object. My question is, is my use in static Connection object thread safe? Or can it cause problems when a lot of users will call the searchUser method?
is my use in static Connection object thread safe?
Absolutely not!
This way the connection going to be shared among all requests sent by all users and thus all queries will interfere with each other. But threadsafety is not your only problem, resource leaking is also your other problem. You're keeping a single connection open during the entire application's lifetime. The average database will reclaim the connection whenever it's been open for too long which is usually between 30 minutes and 8 hours, depending on DB's configuration. So if your web application runs longer than that, the connection is lost and you won't be able to execute queries anymore.
This problem also applies when those resources are held as a non-static instance variable of a class instance which is reused multiple times.
You should always acquire and close the connection, statement and resultset in the shortest possible scope, preferably inside the very same try-with-resources block as where you're executing the query according the following JDBC idiom:
public User find(String username, String password) throws SQLException {
User user = null;
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, username, email FROM user WHERE username=? AND password=md5(?)");
) {
statement.setString(1, username);
statement.setString(2, password);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getLong("id"));
user.setUsername(resultSet.getString("username"));
user.setEmail(resultSet.getString("email"));
}
}
}
return user;
}
Note that you should not return a ResultSet here. You should immediately read it and map it to a non-JDBC class and then return it, so that the ResultSet can safely be closed.
If you're not on Java 7 yet, then use a try-finally block wherein you manually close the closeable resources in the reverse order as you've acquired them. You can find an example here: How often should Connection, Statement and ResultSet be closed in JDBC?
If you worry about connecting performance, then you should be using connection pooling instead. This is built-in into many Java EE application servers and even barebones servletcontainers like Tomcat supports it. Just create a JNDI datasource in the server itself and let your webapp grab it as DataSource. It's transparently already a connection pool. You can find an example in the first link of the list below.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
When my app loses connection, how should I recover it?
Am I Using JDBC Connection Pooling?
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
DAO tutorial with JDBC
If you are only running Select queries (searchUser sounds like only selecting data) there will be no issues, apart from thread contention.
As far as I know, a Connection can only handle one query at a time, so by using a single instance you will essentially serialize database access. But this does not necessarily mean, it is always safe to access a database like this in a multi threaded environment. There might still be issues if concurrent accesses are interleaving.
I have a main class, a login class and a gui class.
Within my main I am creating a database connection using the Singleton pattern - only one instance of this connection.
I want to access the database connection from login, to verify users upon logging into the system.
My connection method within main:
/**
* Use the Singleton pattern to create one Connection
*/
private static Connection getConnection() {
if (conn != null) {
return conn;
}
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage() + " load driver error");
System.exit(0);
}
try {
//conn = DriverManager.getConnection(host);
conn = DriverManager.getConnection(host + "create=true", dbUsername, dbPassword);
} catch (SQLException e) {
displayErr("Get connection error: ", e);
System.exit(0);
}
return conn;
}
Now, I want to create a login method where I need to use the connection conn. The method is static and I cannot use conn.
I'm sure this is wrong but I've also tried making a public method which returns the connection conn and then tried calling that method from Main.
conn = Main.returnConnection();
What should I do in this situation? Pretty confused at how I'm supposed to model this.
Your approach is so primitive when it's compared with Connection Pooling. Connection pool means a pool that includes cached, reusable connections those can be used in future requests. As you said opening a connection for each user is an expensive process also giving a static connection for each user occurs conflictions. Connection pooling is the standart that should be used in these kind of circumstances.
connection = connectionPool.getConnection();
Upper code means get a connection from the pool, if all connections are already allocated, mechanism automatically creates a new one.
The most popular libraries are:
BoneCP
Apache DBCP
C3p0
I figured out the purpose of the Singleton pattern is to create one instance of something and allow it to be seen by everyone.
So I made it public static void instead and can now access the connection, without making a new one each time.
Correct me if I am wrong but this works fine.
i'm gonna create class that will operate on database. The class will have functions addRecord(), getAllRecords(), stuff like that. I'm looking for a good approach to design the class. Should i have to:
1) create new Connection for every function. Like this:
void readRecords(){
try {
Connection con = DriverManager.getConnection (connectionURL);
Statement stmt = con.createStatement();
ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies");
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate");
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
con.close();
}
}
or
2) it's better to have one connection as a memeber variable
class MyClass{
private Connection con;
public MyClass(){
con = DriverManager.getConnection (connectionURL);
}
}
and create just the statement for every function.
3) or something else...
Both approaches are bad. The first one won't allow you to implement proper transaction management, since you can't call several methods inside the same transaction. The latter one requires unnecessary creation of multiple objects.
The best approach would be to introduce a notion of the current connection, which can be obtained from some kind of transactional context. Basically, it should look like this:
beginTransaction(...); // Opens connection and starts transaction
readRecords(...); // Uses the current connection
addRecord(...);
...
commitTransaction(...); // Commits transaction and closes connection
The simpliest but not very elegant implementation is to open a Connection inside the calling method (which defines boundaries of the transaction) and pass it to your methods as a parameter.
More sophisticated solution is to create a static ThreadLocal storage for the current Connection, place it there when you start a transaction and obtain it from that storage inside your methods. Some frameworks implement this approach implicitly, for example, Spring Framework.
Note that connection pooling is completely orthogonal to these matters.
If there are frequent regular jdbc calls, then use a database connection pool.
Connection pooling is the way to go. The biggest reason is that on average the time it takes for the DB access (DML etc) is much smaller than the time it takes to create a connection and then close the connection. Additionally, don't forget to close your ResultSet, PreparedStatement and Connection variables after the transaction is done.
You can use tomcat or apache connection pooling classes.
THese classes are defined for example in the package
org.apache.commons.dbcp.*;
org.apache.tomcat.dbcp.dbcp.*;
where dbcp stands for database connection pooling.