You are on page 1of 13

Connecting to a MySQL Database in Java

In java we have been provided with some classes and APIs with which we can make use of the
database

as we like. Database plays as very important role in the programming because we have to store
the values somewhere in the back- end. So, we should know how we can manipulate the data
in the database with the help of java, instead of going to database for a manipulation. We have
many database provided like Oracle, MySQL etc. We are using MySQL for developing this
application.

In this section, you will learn how to connect the MySQL database with the Java file. Firstly,
we need to establish a connection between MySQL and Java files with the help of MySQL
driver . Now we will make our account in MySQL database so that we can get connected to
the database. After establishing a connection we can access or retrieve data form MySQL
database. We are going to make a program on connecting to a MySQL database, after going
through this program you will be able to establish a connection on your own PC.

Description of program:

This program establishes the connection between MySQL database and java files with the help
of various types of APIs interfaces and methods. If connection is established then it shows
"Connected to the database" otherwise it will displays a message "Disconnected from
database".

Description of code:

Connection:
This is an interface in java.sql package that specifies connection with specific database like:
MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the
context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string
type value (driver) after that matches class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be
register with this class.

getConnection(String url, String userName, String password):


This method establishes a connection to specified database url. It takes three string types of
arguments like:

url: - Database url where stored or created your database


userName: - User name of MySQL
password: -Password of MySQL

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the
database.

printStackTrace():
The method is used to show error messages. If the connection is not established then exception
is thrown and print the message.

Here is the code of program:

import java.sql.*;

public class MysqlConnect{


public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Creating a Database in MySQL


After establishing the connection with MySQL database by using the JDBC driver, you will
learn how we can create our database. A database is a large collection of data or information
stored in our computer in an arranged way. It helps us for accessing, managing and updating the
data easily. In this example we are going to create a database by MySQL and with the help of
some java methods and SQL statement. A RDBMS (Relational Database Management System)
is a type of DBMS (Database Management System

) which stores the data in the form of tables. So, we can view and use the same database in many
different ways.
Description of program:

Firstly this program establishes the connection with MySQL database and takes a database name
as its input in the database query and only after that it will create a new database and show a
message "1 row(s) affected" otherwise, it displays "SQL statement is not executed!".

Description of code:

CREATE DATABASE db_name;


Above code is used for creating a new database. It takes a database name and then a new
database is created by that name.

Here is the code of program:

import java.io.*;
import java.sql.*;

public class CreateDatabase{


public static void main(String[] args) {
System.out.println("Database creation example!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("Enter Database name:");
String database = bf.readLine();
st.executeUpdate("CREATE DATABASE "+database);
System.out.println("1 row(s) affacted");
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

Creating a Database Table


Database: A database is a large collection of data or information to stored in our computer

in an arranged way. It helps us for accessing, managing and updating the data easily. In this
example we are using MySQL database, which is a RDBMS. A RDBMS (Relational Database
Management System) is a type of DBMS (Database Management System) which stores the data
in the form of tables. RDBMS is very powerful as it doesn't need to aware how the data is related
or how it is going to be extracted from the database. So, we can view the same database in many
different ways.

Table: A table is basic component of database (DB) that has number of rows and columns. All
tables are stored in a specific database.

Here we are providing you an example with code and it's description that helps you to create a
database table by using java file. Brief description given below:

Description of program:

Firstly in this program we are going to establish the connection with database and creating a
table with some fields. If table name already exists then we are displaying the message "Table
already exists!".

Description of code:

Statement:
It is a interface. Statement object executes the SQL statement and returns the result it produces.

createStatement():
It is a method of Connection interface. which returns Statement object. This method will
compile again and again whenever the program runs.

CREATE TABLE table_name(field_name):


An appropriate code used for creating a table with given field name.

executeUpdate(String table):
This method also executes SQL statement that may be INSERT, UPDATE OR DELETE
statement are used in the code. It takes string types parameters for SQL statement. It returns int.

Here is the code of program:

import java.sql
.*;

public class CreateTable{


public static void main(String[] args) {
System.out.println("Table Creation Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name va
rchar(10))";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
}
catch(SQLException s){
System.out.println("Table all ready exists!");
}
con.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}

Creating a MySQL Database Table to store


Java Types

Dear user, consider a case where we need to store a java types in our database table. Now one
question may arise in your mind that whether the MySQL supports java types or not. This
section describes how to create a table in MySQL database that stores all java types. Here we are
providing you an example with code for creating a table to store java types. Brief description is
given below:

Description of program:

In this program we are going to establish the connection between MySQL database table and
java file. After the connection has been established creates a database table for storing all java
types. We have used most of the java types provided to us by the jdbc.

Here is the code of program:

import java.sql.*;

public class CreateMySqlTable{

public static void main(String[] args) {


System.out.println("Creating a Mysql Table to Store Java Types!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
<<<<<<< CreateMySqlTable.shtml String table =
"CREATE TABLE java_DataTypes2

("+ "typ_boolean BOOL, "


======= String table
= "CREATE TABLE java_DataTypes2("+ "typ_boolean BOOL, "
>>>>>>> 1.7
+ "typ_byte TINYINT, "
+ "typ_short SMALLINT, "
+ "typ_int INTEGER, "
+ "typ_long BIGINT, "
+ "typ_float FLOAT, "
+ "typ_double DOUBLE PRECISION, "
+ "typ_bigdecimal DECIMAL(13,0), "
+ "typ_string VARCHAR(254), "
+ "typ_date DATE, "
+ "typ_time TIME, "
+ "typ_timestamp TIMESTAMP, "
+ "typ_asciistream TEXT, "
+ "typ_binarystream LONGBLOB, "
+ "typ_blob BLOB)";

st.executeUpdate(table);
System.out.println(table);

con.close();
}
catch (SQLException s){
System.out.println
("Table is all ready exists!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

Description of Database Table


This section introduces you how to get the detailed information about the database table. As we
all know that, table has some specific information like: field, type, null etc. But how to get all
those information by the database. By using a simple query we can get all information about the
table like the number of columns and rows in it, its type, whether the field is null or not, whether
the column is unique or primary and much more.

Description of program:

While making this program firstly we should establish the connection with MySQL database
through the JDBC driver. When the connection has been established, pass the table name in the
database query and use some java methods to get the detail description of table. When the
program will gets execute then it will show field name, type and null of the database table. If
any field have null value then shows "YES" and if not null then shows "NO". If any problem is
created at the time of query, it will show "SQL statement is not executed!".

Description of code:

DESCRIBE table_name;
This code is used to know the brief description of a database table. It takes the name of that table
of which we want to see the description.

getColumns(String cat, String sche, String tab, String col_pat)::


This method returns ResultSet object and provides descriptions of table. It takes four string type
arguments as given below:
String cat: This is a table catalog. It may be null value.
String sche: It shows schema of table. It may be null value.
String tab: This is a table name. It must require for getting the information.
String col_pat: It shows column name pattern.

COLUMN_NAME: Shows column name


TYPE_NAME: data types of column like: integer, varchar, char etc.
COLUMN_SIZE: Column size
NULLABLE: column can be null.

Here is the code of program:

import java.io.*;
import java.sql.*;

public class DiscriptionTable{


public static void main(String[] args) {
System.out.println("See Description of Table Example!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.i
n));
System.out.println("Enter table name:");
String table = bf.readLine();
ResultSet rs = st.executeQuery("DESCRIBE "+table);
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
for (int i = 1; i <= col; i++){
String col_name = md.getColumnName(i);
System.out.print(col_name+"\t");
}
System.out.println();
DatabaseMetaData dbm = con.getMetaData();
ResultSet rs1 = dbm.getColumns(null,"%",table,"%");
while (rs1.next()){
String col_name = rs1.getString("COLUMN_NAME");
String data_type = rs1.getString("TYPE_NAME");
int data_size = rs1.getInt("COLUMN_SIZE");
int nullable = rs1.getInt("NULLABLE");
System.out.print(col_name+"\t"+data_type+"("+data_size+")"+"\t");
if(nullable == 1){
System.out.print("YES\t");
}
else{
System.out.print("NO\t");
}
System.out.println();
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

An Overview of Java Database Connectivity


• December 18, 2001
• By Anand Narayanaswamy
• Bio »
• Send Email »
• More Articles »

[This article assumes you have a basic understanding of Java application and applet
programming.]

Suppose you have a set of records in an Access database that you have to view through a front-
end tool. You can design a user interface by using various programming languages such as
Visual Basic, Visual C++, etc. Java, however, provides a more consistent approach in developing
these interfaces through the javax.swing package. Moreover, Java provides the Java Database
Connectivity (JDBC) API, with which you can connect your app to any database designed either
using Microsoft Access or SQL Server. In this article, we will examine the basic steps required
to handle JDBC using javax.swing for creating user interfaces.

Before proceeding further, let us take a quick look at Microsoft's Object Database Connectivity
(ODBC) and the preference of JDBC over ODBC. The ODBC API offers connectivity to almost
all databases on almost all platforms and is the most widely used programming interface for
accessing relational databases. But ODBC cannot be used directly with Java programs due to
various reasons.

1. ODBC uses a C interface. This has drawbacks in security, implementation,


robustness, etc.
2. ODBC makes use of pointers (which have been removed from Java).

• Post a comment
• Email Article
• Print Article
• Share Articles
o Digg
o del.icio.us
o Slashdot
o DZone
o Reddit
o StumbleUpon
o Facebook
o FriendFeed
o Furl
o Newsvine
o Google
o LinkedIn
o MySpace
o Technorati
o Twitter
o Windows Live
o YahooBuzz

Hence JDBC came into existence. If you've done database programming using Visual Basic,
then you will be familiar with ODBC. You can connect a VB application to an Access database
or an Oracle table directly via ODBC. Since Java is a product of Sun Microsystems, you have to
make use of JDBC along with ODBC in order to develop Java database applications. JDBC is a
set of Java APIs for executing SQL statements. This API consists of a set of classes and
interfaces to enable programmers to write pure database applications.

Let us now examine the basic steps required in all Java programs to handle JDBC.
Step 1: Loading Drivers

First, you have to load the appropriate driver. You can use one driver from the available four.
However, the JDBC-ODBC driver is the most preferred among developers. In order to load the
driver, you have to give the following syntax:

Class.ForName("sun.jdbc.odbc.JdbcOdbcDriver");

Step 2: Making a Connection

The getConnection() method of the Driver Manager class is called to obtain the Connection
object. The syntax looks like this:

Connection conn = DriverManager.getConnection("jdbc:odbc:<DSN NAME>");

Here, note that getConnection() is a static method, meaning it should be accessed along with
the class associated with the method. You have to give the Data Source Name as a parameter to
this method. (See section below for setting up the Data Source Name in your computer.)

Step 3: Creating JDBC Statements

A Statement object is what sends your SQL Query to the Database Management System. You
simply create a statement object and then execute it. It takes an instance of active connection to
create a statement object. We have to use our Connection object "conn" here to create the
Statement object "stmt". The code looks like this:

Statement stmt = conn.createStatement();

Step 4: Executing the Statement

In order to execute the query, you have to obtain the Result Set object (similar to Record Set in
Visual Basic) and a call to the executeQuery() method of the Statement interface. You have to
pass a SQL query like select * from students as a parameter to the executeQuery()
method. If your table name is different, you have to substitute that name in place of students.
Actually, the RecordSet object contains both the data returned by the query and the methods for
data retrieval.

The code for the above step looks like this:

ResultSet rs = stmt.executeQuery("select * from students");

If you want to select only the name field, you have to issue a SQL command like Select Name
from Student. The executeUpdate() method is called whenever there is a delete or an update
operation.
Step 5: Looping Through the ResultSet

The ResultSet object contains rows of data that is parsed using the next() method, such as
rs.next(). We use the getXXX() method of the appropriate type to retrieve the value in each
field. For example, if your first field name is ID, which accepts Number values, then the
getInt() method should be used. In the same way, if the second field Name accepts integer
String values, then the getString() method should be used, like the code given below:

System.out.println(rs.getInt("ID"));

Step 6: Closing the Connection and Statement Objects

After performing all the above steps, you have to close the Connection and RecordSet objects
appropriately by calling the close() method. For example, in our code above, we will close the
object as conn.close()and statement object as stmt.close().

The code for the sample program is shown below for your reference:

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Datas extends JFrame implements ActionListener {

JTextField id;
JTextField name;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res;
static Connection conn;
static Statement stat;

public Datas() {
super("Our Application");
Container c = getContentPane();
c.setLayout(new GridLayout(5,1));
id = new JTextField(20);
name = new JTextField(20);
next = new JButton("Next");
p = new JPanel();
c.add(new JLabel("Customer ID",JLabel.CENTER));
c.add(id);
c.add(new JLabel("Customer Name",JLabel.CENTER));
c.add(name);
c.add(p);
p.add(next);
next.addActionListener(this);
pack();
setVisible(true);
addWindowListener(new WIN());

public static void main(String args[]) {


Datas d = new Datas();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cust"); // cust is the
DSN
Name
stat = conn.createStatement();
res = stat.executeQuery("Select * from Cutomers"); // Customers is
the table name
res.next();

}
catch(Exception e) {
System.out.println("Error" +e);
}
d.showRecord(res);
}

public void actionPerformed(ActionEvent e) {


if(e.getSource() == next) {
try {
res.next();
}
catch(Exception ee) {}
showRecord(res);
}
}

public void showRecord(ResultSet res) {


try {
id.setText(res.getString(1));
name.setText(res.getString(2));
}
catch(Exception e) {}

}//end of the main

//Inner class WIN implemented


class WIN extends WindowAdapter {
public void windowClosing(WindowEvent w) {
JOptionPane jop = new JOptionPane();

jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAGE);

} //end of the class


How to Create a Data Source Name

Follow these steps to create a Data Source Name in Windows

• Open ODBC 32-bit Icon from the control panel. (Start | Settings)
• Click on the Add button and select Microsoft Access Driver.
• Select the appropriate driver if you are using other databases.
• Enter a name as Data Source Name and browse for your database by clicking
the Select button.
• You can also write a short description, but this is optional.
• Finally, click on the Finish button.

Installation Instructions for the Sample Program

1. Copy the program code included with this article. You can also download the
same by clicking here (ZIP file). This file contains the required Access
database and Java files.
2. Place these files in a appropriate directory and set up the Data Source Name
as described above.
3. Compile and execute the program by using the command javac and java

Suggested Reading

1. Java Programming Bible by Aaron Walsh and John Fronckowiak, IDG Books
Worldwide, First Reprint (2000)
2. Java 2 Complete Reference by Patrick Naughton and Herbert Schildt, Third
Edition.

About the Author

You might also like