How to check the connection status in java using jdbc connection? - java

How to handle sql exceptions in Msaccess jdbc connection? I'm retrieving data from msaccess using jdbc connection in java. If connection fail i need to show-up the custom message instead of throwing exception.
public static Connection getConnection() {
Connection connection = null;
try
{
String url = "jdbc:odbc:db1";
String username = "";
String password = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection= DriverManager.getConnection(url, username, password);
}
catch(Exception e)
{
System.out.println("Report");
}
return connection;
}
But its not handling the custom message.its throwing error :
java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object

The location where you are calling getConnection, provide custom message there by handling exception:
Connection con = null;
try {
con = DatabaseUtil.getConnection();
...
...
}catch(Exception e) {
//show message, dialog box, whatever
} finally {
if(con != null) {
try{
con.close();
}catch(SQLException sqe){
//yet another message, unable to close connection cleanly.
}
}
}
P.S. Its a bad idea to declare "Exception", you should always try to throw most relevant exception from your method. SQLException makes more sense in DatabaseUtil.getConnection
P.P.S. Class.forName(driver); is only required once per JVM invocation (for JDBC driver registration). Hence, the appropriate place to register your JDBC drivers is in a static initializer (which is called once when your class is loaded for the first time).

You can not avoid exceptions. Instead of throwing them, you can handle them by using
try{
// do Something
} catch(SqlException e){
// catch exception
} finally {
// do something to get recover
}
For more info follow this link

You cannot avoid the SQLException being thrown. The JDBC APIs don't provide a method to test connection liveness.
To test if a JDBC connection is (still) valid, you perform a simple query. The "dummy query" idiom for doing this varies with the database, but any query on any of your tables will suffice. If the connection is not alive you will get an exception ... which you need to handle.
However it is possible for the database connection to die between you testing the connection and then performing your real query (or whatever). So (IMO) you are better off just writing your code so that it can deal with the SQLException in a real query ... and not bother probing. This also gives better performance, because repeatedly testing to see if a JDBC connection is alive is going to add useless load to your application ... and the database.

Related

if I forget to close the connection to the database

if i do close to connection database instead if i do close my resultSet ,what happend ?
I did write example to under.
For example.
Database.java
public class Database{
try{
Connection con;
PreparedStatement statement;
ResultSet resultSet;
public static void main{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/database";
String _username="root";
String _password = "password";
Connection db = DriverManager.getConnection(url,_username,_password);
String sqlQuery = "select * from category";
statement = db.prepareStatement(sqlQuery);
resultSet = statement .executeQuery();
while(resuletSet.next()){
......
}
// i dont close connect.
resultSet.close();
//what happen then it? connection.close() , will it be automatically down ?
}catch(Exception e){
e.printStackTrace();
}
}
}
You're right to close your ResultSet carefully. Leaving those objects around after you finish with them is definitely a way to get memory leaks.
You should also close your Connection objects when you no longer need them. If your Java program terminates any Connection objects you still have open are closed, automatically. If no queries are in progress on those objects then the MySQL server closes the connection and cleans up when Java abandons the connection.
Java since version 7 has a way to manage this cleanly. You can do
try (Connection db = DriverManager.getConnection(url,_username,_password)){
//use the connection object
...
try (ResultSet result = stmt.ExecuteQuery(whatever)) {
// use the resultset
} catch (whatever) { whatever }
}
catch(whatever) { whatever }
This is is a nice way to avoid these leaks; the Connection and ResultSet objects get closed automatically at the end of the try / catch block just as if they were closed in a finally{} clause. It's called automatic resource block management.
Yes, close Connections when you're done with them. If you open a lot of Connection objects without closing them, two bad things happen:
Less bad: your Java program's RAM will leak.
More bad: your MySQL server's connection slots will fill up and it will start rejecting new connections. Client bugs which use up server resources are generally bad bugs.
Failing to close Connections can be pernicious, because typical programs don't use as many of them as ResultSets. So it takes longer to accumulate lots of unclosed connections, and you may not detect the problem while testing. Testers should log into the MySQL server directly and run the SHOW PROCESSLIST; command during system testing to see if unclosed Connections are accumulating.
Close your ResultSets and your Connections.

How should I model my system - database implication

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.

DriverManager.getConnection() returns null, rather than a connection object

I am trying to connect to an Oracle database via JDBC. Using the following code:
Connection c = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
c = DriverManager.getConnection(connURL, userID, password);
} catch (SQLException se) {
System.out.println(se.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
For some reason no exception is thrown but c remains null - what does this mean?
Update:
Turns out we were getting an exception - Class not found: "oracle.jdbc.driver.OracleDriver" - we had the odbc classes outside the classpath.
This would have been easier to spot if you handled your exceptions differently. Just printing the exception message and moving on is rarely the right thing to do. What can you do when the database connection is null? If you throw an exception indicating that the connection isn't available, then whatever routine is trying to get a connection to the database can alert the user to a potential system outage, log the error, and email a system administrator (for example). Just returning null is less obvious to troubleshoot, as you have found.

When destroy the database connection?

I'm working on a project programmed in jsf, but no persistence layer, the queries are plain jdbc in beans. At apllication start the jdbc connection is instantiated and if the user exists und writes his correct password the authentification bean will be instantiated. My problem is, I don't know exactly how to destroy the connection wenn the authentification bean dies for example because of a timeout. My other problem is, how would I know the application is over, if the user don't click the button log out and simply close the browser.
Consider seriuosly using a connection pool. It will make your life easier:)
For example when you authenticate a user, you just grab a connection from the pool, do the validation and then close the connection, which will return it to the pool.
At apllication start the jdbc connection is instantiated
This is the wrong approach. The connection should be opened in the very same try block as you're creating and executing the statement and gathering the results. The connection (and statement and resultset) must be closed in the finally block of this try block.
Not doing so may lead to resource leaking and unexpected (and undesired) application behaviour when this happens and/or when the DB server decides to timeout the connection because it's been kept open for too long by your application.
The following is the basic JDBC idiom:
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SOME_SQL);
resultSet = statement.executeQuery();
// ...
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
To improve connecting performance, you can always use a connection pool, but do not change the basic JDBC idiom of acquiring and closing the resources in the shortest scope in a try-finally block. Most decent servletcontainer/applicationservers ships with builtin connection pooling facilities. As long as it's unclear which one you're using, it's impossible to give a well-suited answer about it.
That said, I would still strongly recommend to detach the persistence layer from your MVC layer. It'll make it better testable, reuseable and maintainable.
See also:
Basic DAO tutorial

java jdbc mysql connector: how to resolve disconnection after a long idle time

I'm using red5 1.0.0rc1 to create an online game.
I'm connecting to a MySQL database using a jdbc mysql connector v5.1.12
it seems that after several hours of idle my application can continue running queries because the connection to the db got closed and i have to restart the application.
how can I resolve the issue ?
Kfir
The MySQL JDBC driver has an autoreconnect feature that can be helpful on occasion; see "Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J"1, and read the caveats.
A second option is to use a JDBC connection pool.
A third option is to perform a query to test that your connection is still alive at the start of each transaction. If the connection is not alive, close it and open a new connection. A common query is SELECT 1. See also:
Cheapest way to to determine if a MySQL connection is still alive
A simple solution is to change the MySQL configuration properties to set the session idle timeout to a really large number. However:
This doesn't help if your application is liable to be idle for a really long time.
If your application (or some other application) is leaking connections, increasing the idle timeout could mean that lost connections stay open indefinitely ... which is not good for database memory utilization.
1 - If the link breaks (again), please Google for the quoted page title then edit the answer to update it with the new URL.
Well, you reopen the connection.
Connection pools (which are highly recommended, BTW, and if you run Java EE your container - Tomcat, JBoss, etc - can provide a javax.sql.DataSource through JNDI which can handle pooling and more for you) validate connections before handing them out by running a very simple validation query (like SELECT 1 or something). If the validation query doesn't work, it throws away the connection and opens a new one.
Increasing the connection or server timeout tends to just postpone the inevitable.
I had the Same issue for my application and I have removed the idle time out tag
Thats it
It really worked fine
try this, I was using the Jboss server, in that i have made the following change in mysql-ds.xml file.
Let me know if you have any more doubts
The normal JDBC idiom is to acquire and close the Connection (and also Statement and ResultSet) in the shortest possible scope, i.e. in the very same try-finally block of the method as you're executing the query. You should not hold the connection open all the time. The DB will timeout and reclaim it sooner or later. In MySQL it's by default after 8 hours.
To improve connecting performance you should really consider using a connection pool, like c3p0 (here's a developer guide). Note that even when using a connection pool, you still have to write proper JDBC code: acquire and close all the resources in the shortest possible scope. The connection pool will in turn worry about actually closing the connection or just releasing it back to pool for further reuse.
Here's a kickoff example how your method retrieving a list of entities from the DB should look like:
public List<Entity> list() throws SQLException {
// Declare resources.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Entity> entities = new ArrayList<Entity>();
try {
// Acquire resources.
connection = database.getConnection();
statement = connection.createStatement("SELECT id, name, value FROM entity");
resultSet = statement.executeQuery();
// Gather data.
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setName(resultSet.getString("name"));
entity.setValue(resultSet.getInteger("value"));
entities.add(entity);
}
} finally {
// Close resources in reversed order.
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
// Return data.
return entities;
}
See also:
DAO tutorial - How to write proper JDBC code
Do you have a validationQuery defined (like select 1)? If not, using a validation query would help.
You can check here for a similar issue.
Append '?autoReconnect=true' to the end of your database's JDBC URL (without the quotes) worked for me.
I saw that ?autoReconnect=true wasn't working for me.
What I did, is simply creating a function called: executeQuery with:
private ResultSet executeQuery(String sql, boolean retry) {
ResultSet resultSet = null;
try {
resultSet = getConnection().createStatement().executeQuery(sql);
} catch (Exception e) {
// disconnection or timeout error
if (retry && e instanceof CommunicationsException || e instanceof MySQLNonTransientConnectionException
|| (e instanceof SQLException && e.toString().contains("Could not retrieve transation read-only status server"))) {
// connect again
connect();
// recursive, retry=false to avoid infinite loop
return executeQuery(sql,false);
}else{
throw e;
}
}
return resultSet;
}
I know, I'm using string to get the error.. need to do it better.. but it's a good start, and WORKS :-)
This will almost all reasons from a disconnect.

Categories

Resources