Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

JDBC-API to connect to a DB

1)Load the Driver class

Class.forName("com.mysql.jdbc.Driver")
this will create an instance of Class for com.mysql.jdbc.Driver 

find the class file and get the binary data
Constructing the class from the binary data.

then the static block of which instantiates a new Driver of this class and registers with DriverManager

static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} .......
}

//added to the drivers in the DriverManager
writeDrivers.addElement(di);
println("registerDriver: " + di);
readDrivers = (java.util.Vector) writeDrivers.clone();
2)Get the connection Object
for (int i = 0; i < drivers.size(); i++) { //iterates over all the drivers list
DriverInfo di = (DriverInfo)drivers.elementAt(i);

try {
println(" trying " + di);
Connection result = di.driver.connect(url, info);

result is the connection object.
Connection newConn = new com.mysql.jdbc.Connection(host(props),
port(props), props, database(props), url, this);

Connection is an interface which is implemented by the providers class

3)create a statement , and execute the query
/* Create a statement*/
Statement statement = connection.createStatement();

String query = "Select * from yourTABLE ";
ResultSet rs = statement.executeQuery(query);

No comments:

Post a Comment

Search 24 Bytes