Title: Key Concept - Connecting to MySQL database using JDBC
Course: CPS 189: Java Certification - Review, Practice & Prepare (Development) > Section: Learning Modules

The following code attempts to connect to a MySQL server via JDBC:

Connection connection = null;

try

{

Class.forName("com.mysql.jdbc.Driver");

connection = DriverManager.getConnection (

"jdbc:mysql://<localhost>:3306/" +

"<database>?user=<UserID>&password=<password>");

System.out.println("Connected to MySQL server.");

}

catch (ClassNotFoundException e1)

{

System.out.println("Error: cannot load JDBC driver class.");

System.out.println("Exception message:\n" + e1.getMessage());

}

catch (SQLException e2)

{

System.out.println("Error: cannot connect to MySQL server.");

System.out.println("Exception message:\n" + e2.getMessage());

}

The Class.forName statement loads and initializes a class during execution.  The fully-qualified class name must be used.  It returns the Class object associated with the class.