JDBC Class.forName(String drivername) Example for MySql Database


 

JDBC Class.forName(String drivername) Example for MySql Database

In this tutorial, we will called the Class.forName(String drivername)that automatically creates an instance of a driver and registers it with the DriverManager.

In this tutorial, we will called the Class.forName(String drivername)that automatically creates an instance of a driver and registers it with the DriverManager.

JDBC Class.forName(String drivername) Example for MySql Database:

In this tutorial, we will called the Class.forName(String drivername)that automatically creates an instance of a driver and registers it with the DriverManager. Now we will create a java class JDBCforName.java and store the information like database url, database name, driver name, database user name, database password to create connection with the MySql database server as:

Connection connection = null;

String url = "jdbc:mysql://192.168.10.13:3306/";

String dbName = "roseindia_jdbc_tutorial";

String driverName = "com.mysql.jdbc.Driver";

String userName = "root";

String password = "root";

Now we will called the Class.forName(String drivername) method and get the connection as:

Class.forName(driverName).newInstance();

connection = DriverManager.

getConnection(url+dbName, userName, password);

The code of the JDBCforName.java is:

import java.sql.*;
public class JDBCforName {
  
  public static void main(String[] args) {
    Connection connection = null;
      String url = "jdbc:mysql://localhost:3306/";
      String dbName = "roseindia_jdbc_tutorial";
      String driverName = "com.mysql.jdbc.Driver";
      String userName = "root";
      String password = "root";
      try{
        Class.forName(driverName).newInstance();
        connection = DriverManager.getConnection(url+dbName, userName, password);
        System.out.println("java Class.forName(String drivername) Example");
      }
      catch (Exception e){
        e.printStackTrace();
      }      
  }
}

Program output:

Download Code

Ads