If
you are communicating to SQL databases using JDBC, the typical steps are like
below.
Step 1: import sql package
import
java.sql.*;
Step 2: Register jdbc driver.
By using below statement, we are loading main driver class into the JVM.
Ex:
Class.forName("com.mysql.jdbc.Driver");
Step 3: Open connection to
database, using DriverManager class.
Ex:
String
url = "jdbc:mysql://localhost/sample";
String
userName = "root";
String
pasword = "tiger";
Connection
con = DriverManager.getConnection(url, userName, pasword);
jdbc:mysql://localhost/sample
Above
string is a database connection string.
jdbc:mysql://
= java database connection to a mysql database
localhost
= mysql database is on local machine
sample
= name of database being connected to
Many
people wonder, how come DriverManager class knows about the
"com.mysql.jdbc.Driver" class.?
All
the magic done by Class.forName method. When you load a class using Class.forName
method, it calls the static block of that class.
"com.mysql.jdbc.Driver" class register itself to the DriverManager
class in its static block.
Let
us see with an example.
Connection.java
package com.sample.app; public class Connection { }
Driver.java
package com.sample.app; public interface Driver { public Connection getConnection(); }
DriverManager.java
package com.sample.app; public class DriverManager { private static Driver driver; public static void registerDriver(Driver driver) { DriverManager.driver = driver; } public static Connection getConnection() { return driver.getConnection(); } }
MyDriver.java
package com.sample.app; public class MyDriver implements Driver { static { System.out.println("Registering MyDriver to DriverManager"); DriverManager.registerDriver(new MyDriver()); } @Override public Connection getConnection() { return new Connection(); } }
Application.java
package com.sample.app; public class Application { public static void main(String args[]) throws Exception { System.out.println("Loading MyDriver class"); Class.forName(MyDriver.class.getName()); DriverManager.getConnection(); } }
Output
Loading
MyDriver class
Registering
MyDriver to DriverManager
You may like
No comments:
Post a Comment