Connecting To A MySQL Database Using Connector
Connecting To A MySQL Database Using Connector
Overview
In this tutorial following topics will be covered:
What are Database URLs in JDBC? Why and how to specify a JDBC Driver name? How to create a connection to a Database? An example on how to connect to a MySQL Database?
URL stands for "Uniform Resource Locator". You will be familiar with HTTP URLs that you normally use to access a web site e.g. http://www.stardeveloper.com. URLs are used to identify a resource using a unique name. Same goes for database URLs in JDBC. JDBC requires that all database connection strings should be represented by URLs. The URLs used in JDBC have following structure:
jdbc:subprotocol:subname
In HTTP you begin a URL with the protocol name i.e. http:, similarly in JDBC driver URLs, you start the URL with protocol name i.e. jdbc:. Next subprotocol represents the database you want to connect to e.g. mysql, oracle, odbc etc. While subname provides additional information on how and where to connect. Tip: If you are familiar with ASP/ASP.NET, a database URL in JDBC is quite similar to a connection string used in an ASP environment to connect to a database.
jdbc:odbc:dsn_name;UID=your_uid;PWD=your_pwd - JDBC-ODBC Bridge Driver URL. jdbc:oracle:thin:@machine_name:port_number:instance_name - Orace Type 4 JDBC Driver. jdbc:mysql://host_name:port/dbname - MySQL Connector/J JDBC Driver.
To load the the driver/s at JVM startup, specify the driver/s in jdbc.drivers system property like this:
To explicitly load the driver, use Class.forName()method in your code like this:
Note: In above examples, "com.mysql.jdbc.Driver" is the name of the JDBC driver that you want to load. The example discussed in this tutorial makes use of the second option discussed above.
Class.forName("com.mysql.jdbc.Driver").newInstance();
JdbcExample2.java
Create a new Java source file and save it as JdbcExample2.java. Copy/paste following code in it:
package com.stardeveloper.example; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JdbcExample2 { public static void main(String args[]) { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret"); if(!con.isClosed()) System.out.println("Successfully connected to " + "MySQL server using TCP/IP..."); } catch(Exception e) { System.err.println("Exception: " + e.getMessage()); } finally { try { if(con != null) con.close(); } catch(SQLException e) {} }
Explanation
Above Java program tries to connect to "test" database installed on your local MySQL server. "test" database is installed on all MySQL servers by default so that is why I am using this database to connect to, otherwise as far as this tutorial is concerned, it won't be accessing any tables in that database. Let us see the code now. The first statement describes that this Java program belongs tocom.stardeveloper.example package:
package com.stardeveloper.example;
Next, we import 3 classes from java.sql package.Connection represents a connection to a database,DriverManager manages JDBC drivers and is used to create connections to databases and SQLException is an exception class which gets thrown in case any error ocurrs in the program.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Once the JDBC driver has been loaded in the JVM, we retrieve a connection to our MySQL database running on the local system using DriverManager.getConnection() method. The first argument to this method is complete database URL, next parameter is the user name and last parameter is the password. Note: You'd want to change the password described here with the actual password that you've setup for your MySQL 'root' account.
try {
Hoa! this is all that is required to successfully connect to a running instance of MySQL server on your local system and print a success message. Let us move on and compile/run our Java program.
Compiling JdbcExample2.java
To compile the JdbcExample2.java program to it's class file and place it according to it's package statements, open command prompt and cd (change directory) into the folder containing JdbcExample2.java, then execute this command:
javac -d . JdbcExample2.java
Note: The zip file that comes with this tutorial contains all the source and class files required to successfully run this Java program. If all goes well you should get a new Java class under the current folder with a directory structure like com/stardeveloper/example/JdbcExample2.class.
Running JdbcExample2.java
Before we try to execute our Java program, make sure that MySQL server is running on your local system. If it not running then start the MySQL database server and move on. To run this program execute following command from the command prompt from the same folder where JdbcExample2.java is residing:
java com.stardeveloper.example.JdbcExample2
If all goes well you should see a success message printed on your console. Here is how it looked when I executed this program on my system:
Congratulations! you've successfully coded, compiled and run your first JDBC program which connects to a MySQL server running on your local system using Connector/J JDBC driver.
Summary
In this tutorial we learned the basics of connecting to a database (MySQL) using a JDBC driver (Connector/J). We learned what are database URLs and why/how to specify JDBC driver names. We then moved on to write a simple Java program which connects to a MySQL database and prints a success message. In next article we will learn on how to create and execute SQL statements against a database using JDBC.