开发者

Connecting Java to a Database?

开发者 https://www.devze.com 2023-02-02 02:28 出处:网络
I have connected Java to MySQL DB with the following code and it is working, Can anyone explain me what eac开发者_如何学Pythonh line does?

I have connected Java to MySQL DB with the following code and it is working, Can anyone explain me what eac开发者_如何学Pythonh 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();


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.


// 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();


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号