satheesh.droid
satheesh.droid

Reputation: 31557

Connecting Java to a Database?

I have connected Java to MySQL DB with the following code and it is working, Can anyone explain me what each line does?

Class.forName("com.mysql.jdbc.Driver").newInstance();
        con = DriverManager.getConnection("jdbc:mysql://10.10.1.1/test","USERNAME","SATHE");
        Statement stmt=con.createStatement();

Upvotes: 2

Views: 222

Answers (4)

Gareth Davis
Gareth Davis

Reputation: 28069

As a side note in 1.6 there is no need for driver registration line:

Class.forName("com.mysql.jdbc.Driver");

As the DriverManager will discover the Driver automatically assuming the jar is on the class-path.

Upvotes: 1

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32014

When com.mysql.jdbc.Driver is loaded in JVM by Class.forName(), some methods such as DriverManager.registerDriver() will be invoked by com.mysql.jdbc.Driver. That is, mysql registers itself in DriverManager. So DriverManager.getConnection() could work.

You could read java source com.mysql.jdbc.Driver to discover it.

Upvotes: 0

javamonkey79
javamonkey79

Reputation: 17785

// loads the vendor specific jdbc library - there are many to choose from
Class.forName("com.mysql.jdbc.Driver").newInstance();

// this is what tells the library to connect, using the vendor specific pattern
con = DriverManager.getConnection("jdbc:mysql://10.10.1.1/test","USERNAME","SATHE");

// this prepares the statement from the connection.
Statement stmt=con.createStatement();

Upvotes: 1

Denis Tulskiy
Denis Tulskiy

Reputation: 19187

First line loads the database driver by loading the driver class, because, I guess, the DriverManager looks for loaded classes that are jdbc drivers.

Second establishes connection to the database with given path, username and password. It returns you a connection object that allows you to manipulate the session, prepare statements etc.

Third creates a statement. Statement object is used for executing queries.

Upvotes: 2

Related Questions