Home Tutorial Java Jdbc Jdbcbatch JDBC Class.forName(String drivername) Example for MySql Database

 
 

Share on Google+Share on Google+
JDBC Class.forName(String drivername) Example for MySql Database
Posted on: October 15, 2010 at 12:00 AM
Advertisement
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

Advertisement

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


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 15, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com