A Connection is the session between your java program and database. Whenever you do anything with database you have to have a connection object. There are many ways we can establish the connection.
The connection object is obtained by the DriverManager.getConnectyion method by supplying the Database location and authentication credentials.
The following are the ways to obtain a Connection object of the database:-
1. DriverManager.getConnection(String URL)
2. DriveManager.getConnection(String URL,String Username, String Password)
3. DriverManager.getConnection (String URL, java.util.Properties props)
4. Driver.connect(String URL, java.util.Properties props)
The coming example will cover all the ways for Connection.
package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.gjt.mm.mysql.Driver;
public class JDBCConnectionExample {
public static void main(String[] args) {
try {
/** Loading the driver*/
Class.forName("com.mysql.jdbc.Driver");
/** Getting Connection Type 2*/
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
/** Type 3*/
/*Properties props = new Properties ();
props.put("user","root");
props.put("password","root");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",props);*/
/** Type -4 */
Properties props = new Properties ();
props.put("user","root");
props.put("password","root");
Driver driver= new Driver();
Connection con = driver.connect("jdbc:mysql://localhost:3306/test",props);
System.out.println("Connection Established");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:-
Connection Established
Java Discussion
- - Interviewing Next week -
- - Sudoku solver
- - Setting tab order in swin
- - Java opportunities
- - Struts



