How to connect to an SQL database with JDBC

June 20, 2008

About JDBC

If you have java applets or other java applications and you want to connect them with standard SQL databases like SLQ Server, Oracle, Informix, Sybase and others JDBC is the one who can help you to do that.The combination of Java’s JDBC and standard SQL makes a simple and powerful database solution. Using JDBC things are easy without making the complex tasks too difficult either.

During this article we’ll teach you haw to establish a connection between your java applications and SQL data base and we’ll do that step-by-step to understand better.

Obtaining the JDBC driver

For using JDBC you need to install the JAVA JDK. If you don’t have it already installed you can download it(free) at Sun’s Java web site .Also many IDE’s have already integrated it so you have nothing more to do just to use.Next thing you have to do is to obtain correctly the JDBC driver.In most cases the JDBC driver will be provided by your database vendor.Once you have this driver you have to install it.

Establishing a connection is a two-step process

If you installed the JDBC driver correctly it’s very easy to establish the connection between java application and the SQL database. So for establishing that connection you have to follow the next two steps:

- Load the JDBC driver.

- Establish the connection.

For undestanding better what you have to do we give you an example:

    // Establish a connection to a mSQL database using JDBC.import java.sql.*;class JdbcTest1 { public static void main (String[] args) { try { // Step 1: Load the JDBC driver. Class.forName(”com.imaginary.sql.msql.MsqlDriver“); // Step 2: Establish the connection to the database. String url = “jdbc:msql://www.myserver.com:1114/contact_mgr“; Connection conn = DriverManager.getConnection(url,”user1″,”password”); } catch (Exception e) { System.err.println(”Got an exception! “); System.err.println(e.getMessage()); } } }

The JDBC Driver

The name of the JDBC driver will be supplied to you by your database
vendor. As you can see in the class.forName() statements, these
names will vary.

The URL

The syntax of the DriverManager.getConection() method is: DriverManager.getConnection(String url, String username, String password);

Username and password are used for login to the data base.

 

Post a comment

Name (required)

Mail (will not be published) (required)

Website

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word