How to connect to a database using JDBC

This example shows how to connect to a database using JDBC. (In this example we will connect to Oracle database) .

You will need to add the odbc{x}.jar library to your classpath, downloadable from Oracle’s website.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcExample {

 public static void main(String[] args) {
  
  try{
  	// register the driver
  	Class.forName("oracle.jdbc.driver.OracleDriver");
  	// create the connexion
  	Connection connection
            =DriverManager.getConnection(
               "jdbc:oracle:thin:@localhost:1521:xe", "system", "pwd"
                );
  } catch (ClassNotFoundException e) {
    // the driver was not found
    e.printStackTrace();
  } catch (SQLException e) {
    // Error when connecting to database
    e.printStackTrace();
  }
 }

}

 

You like this content ? Share it with you entourage !

Leave a Reply

Your email address will not be published.