0% found this document useful (0 votes)
37 views

Connecting To Mysql Using The JDBC Drivermanager Interface

This document discusses connecting to a MySQL database from Java code using the JDBC DriverManager interface. It shows how to register the MySQL Connector/J driver class name to make connections. The code example loads the MySQL JDBC driver class, catches any errors, and allows connections to be established between Java applications and MySQL.

Uploaded by

Shalu Ojha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Connecting To Mysql Using The JDBC Drivermanager Interface

This document discusses connecting to a MySQL database from Java code using the JDBC DriverManager interface. It shows how to register the MySQL Connector/J driver class name to make connections. The code example loads the MySQL JDBC driver class, catches any errors, and allows connections to be established between Java applications and MySQL.

Uploaded by

Shalu Ojha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.sql.

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

// Notice, do not import com.mysql.jdbc.*


// or you will have problems!

public class LoadDriver {


public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations

Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
}

Connecting to MySQL Using the JDBC


DriverManager Interface
When you are using JDBC outside of an application server, the DriverManager class manages
the establishment of connections.
Specify to the DriverManager which JDBC drivers to try to make Connections with. The
easiest way to do this is to use Class.forName() on the class that implements the
java.sql.Driver interface. With MySQL Connector/J, the name of this class is
com.mysql.jdbc.Driver. With this method, you could use an external configuration file to
supply the driver class name and driver parameters to use when connecting to a database.

The following section of Java code shows how you might register MySQL Connector/J from
the main() method of your application. If testing this code, first read the installation section at
Chapter  3, Connector/J Installation, to make sure you have connector installed correctly and
the CLASSPATH set up. Also, ensure that MySQL is configured to accept external TCP/IP
connections.

You might also like