tags:

views:

140

answers:

3

How to create a jdbc connection in java?

+4  A: 

See sun's jdbc tutorial for begginers

Particularly http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html

First, you need to establish a connection with the DBMS you want to use. Typically, a JDBC™ application connects to a target data source using one of two mechanisms:

DriverManager: This fully implemented class requires an application to load a specific driver, using a hardcoded URL. As part of its initialization, the DriverManager class attempts to load the driver classes referenced in the jdbc.drivers system property. This allows you to customize the JDBC Drivers used by your applications.

DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object's properties are set so that it represents a particular data source.

Connection con = DriverManager.getConnection
           ( "jdbc:myDriver:wombat", "myLogin","myPassword");
Tom
+1  A: 

To create a connection, you need to load the driver first. For example, for MySQL:

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

The driver class to load obviously depends on the JDBC driver (and thus on the database) that needs to be on the classpath.

Then, make the connection:

String url = "jdbc:mysql://host_name:port/dbname";
String user = "scott";
String pwd = "tiger";
Connection con = DriverManager.getConnection(url, user, pwd);

The url is the "connection url" and identifies the database to connect to. Again, the syntax will depend on the JDBC driver you're using. So, refer to the documentation of your JDBC driver.

Establishing a Connection in The Java Tutorials is indeed a good reference.

Pascal Thivent
+1  A: 

Have a look at ABCs of JDBC.

Lalith
its easy as 1 2 3..
Tom
@Tom: Or simple as do re mi...
Bill the Lizard