JDBC connection timeout

In this Tutorial we want to describe you a code that help you in understand Jdbc connection timeout.

JDBC connection timeout

JDBC connection timeout

     

The Tutorial describe you a JDBC Connection timeout. In this program, we want to explain you a code that help you in understand the maximum time for which driver can wait to connect database.

Understand with Example

The code include a class JDBC Connection Timeout, inside the main method we include the list of following steps -

  1. The first step is to import a package name Java.sql.*  -  This package import the definition of all classes present in this package.
  2. Loading a driver -The next step is load a driver by calling class.forname( ) and passed the driver as argument in it. 
  3. DriverManager.getLoginTimeout( ) -This method return the maximum time for the driver can wait while trying to connect a database.
  4. DriverManager.getconnection ( ) - This method attempt to connect a url and database.
  5. con.createstatement ( ) - This method is used to return an Sql object. Once a connection is built ,your application page can interact with backend database. A connection object is used further to send and execute SQL Statement to a backend database
  6. next(  ) - This method return you the next successive element in series.
  7. execute query - This method is used to retrieve a record from a database using select queries in sql .

On the execution of code,the code attempt to establish a connection between url and database in 10 sec.Finally the println print the element from the database.

JdbcConnectionTimeout.java



import java.sql.*;
public class JdbcConnectionTimeout {
  public static void main(String args[]) {
  Connection con = null;
  Statement st = null;
  ResultSet rs = null;
  String url = "jdbc:mysql://localhost:3306/";
  String db = "komal";
  String driver = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "root";
  try {
  Class.forName(driver);
  
;
  System.out.println("Connection Login Timeout : " +
  DriverManager.getLoginTimeout());
  con = DriverManager.getConnection(url + db, user, pass);
  st = con.createStatement();
  String sql = "select * from customer";
  rs = st.executeQuery(sql);
  System.out.println("First Name  \tLast Name");
  while (rs.next()) {
  System.out.print(rs.getString("First_Name") + " \t");
  System.out.println(rs.getString("Last_Name"));
  }
  catch (Exception e) {
  System.out.println(e);
  }
  }

Output

Connection Login Timeout : 10
First Name  	Last Name
girish   	tewari
mahendra   	singh
komal   	singh
yogesh   	pandey
pinku   	tripathi
deepak   	tripathi 

Download code