Vous êtes sur la page 1sur 13

Data types of MySQL and Java programming language are not same, its need some mechanism for

transferring data
between an database using MySQL data types and a application using Java data types. We need to provide Java
mappings for the common MySQL data types. We have to confirm that we have proper type information then only
we can correctly store and retrieve parameters and recover results from MySQL statements.

There is no particular reason that the Java data type needs to be exactly isomorphic to the MySQL data type. For
example, Java String don't precisely match any of the MySQL data CHAR type, but it gives enough type information
to represent CHAR, VARCHAR or LONGVARCHAR successfully.

The following table represent the default Java mapping for various common MySQL data types:

MySQL Type Java Type

CHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BIT boolean
REAL float
FLOAT double
DOUBLE double
BINARY byte []
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Tiimestamp


MySQL data types CHAR, VARCHAR, LONGVARCHAR are closely related. CHAR represents a small,
fixed-length character string, VARCHAR represents a small, variable-length character string, and
LONGVARCHAR represents a large, variable-length character string. There is no need for Java programmer
to distinguish these three MySQL data types. These can be expressed identically in Java. These data types
could be mapped in Java to either String or char[]. But String seemed more appropriate type for normal use.
Java String class provide a method to convert a String into char[] and a constructor for converting a char[] into
a String.

The method ResultSet.getString allocates and returns a new String. It is suitable for retrieving data from
CHAR, VARCHAR and LONGVARCHAR fields. This is suitable for retrieving normal data, but
LONGVARCHAR MySQL type can be used to store multi-megabyte strings. So that Java programmers
needs a way to retrieve the LONGVARCHAR value in chunks. To handle this situation, ResultSet interface
have two methods for allowing programmers to retrieve a LONGVARCHAR value as a Java input stream
from which they can subsequently read data in whatever size chunks they prefer. These methods are
getAsciiStream and getCharacterStream, which deliver the data stored in a LONGVARCHAR column as a
stream of ASCII or Unicode characters.


The NUMERIC and DECIMAL MySQL data types are very similar. They both represent fixed point
numbers where absolute precision is required. The most convenient Java mapping for these MySQL data type
is java.math.BigDecimal. This Java type provides math operations to allow BigDecimal types to be added,
subtracted, multiplied, and divided with other BigDecimal types, with integer types, and with floating point

We also allow access to these MySQL types as simple Strings and char []. Thus, the Java programmers can
use the getString() to retrieve the NUMERICAL and DECIMAL results.


These MySQL data types are closely related. BINARY represents a small, fixed-length binary value,
VARBINARY represents a small, variable-length binary value and LONGVARBINARY represents a large,
variable-length binary value. For Java programers there is no need to distinguish among these data types and
they can all be expressed identically as byte arrays in Java. It is possible to read and write SQL statements
correctly without knowing the exact BINARY data type. The ResultSet.getBytes method is used for
retrieving the DECIMAL and NUMERICAL values. Same as LONGVARCHAR type,
LONGVARBINARY type can also be used to return multi-megabyte data values then the method
getBinaryStream is recommended.

4. BIT

The MySQL type BIT represents a single bit value that can be 'zero' or 'one'. And this MySQL type can be
mapped directly to the Java boolean type.


The MySQL TINYINT type represents an 8-bit integer value between 0 and 255 that may be signed or
unsigned. SMALLINT type represents a 16-bit signed integer value between -32768 and 32767. INTEGER
type represents a 32-bit signed integer value between -2147483648 and 2147483647. BIGINT type represents
an 64-bit signed integer value between -9223372036854775808 and 9223372036854775807. These MySQL
TINYINT, SMALLINT, INTEGER, and BIGINT types can be mapped to Java's byte, short, int and long data
types respectively.


The MySQL REAL represents a "single precision" floating point number that supports seven digits of
mantissa and the FLOAT and DOUBLE type represents a "double precision" floating point number that
supports 15 digits of mantissa. The recommended Java mapping for REAL type to Java float and FLOAT,
DOUBLE type to Java double.


These three MySQL types are related to time. The DATE type represents a date consisting of day, month, and
year, the TIME type represents a time consisting of hours, minutes, and seconds and the TIMESTAMP type
represents DATE plus TIME plus a nanosecond field. The standard Java class java.util.Date that provides
date and time information but does not match any of these three MySQL date/time types exactly, because it
has DATE and TIME information but no nanoseconds.

That's why we define three subclasses of java.util.Date. These are:

java.sql.Date for SQL DATE information.

• java.sql.Time for SQL TIME information.

• java.sql.Timestamp for SQL TIMESTAMP information.

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:

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.

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

This method is used for disconnecting the connection. It frees all the resources occupied by the database.

The method is used to show error messages. If the connection is not established then exception is thrown and print the

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 {
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
System.out.println("Disconnected from database");
} catch (Exception e) {

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:


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

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;
con = DriverManager.getConnection
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){

Download this example.

Output of program:


Database creation example!
Enter Database name:
1 row(s) affacted

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

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:

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

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";
con = DriverManager.getConnection(url+dbName, userName, password);
Statement st = con.createStatement();
String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))";
System.out.println("Table creation process successfully!");
catch(SQLException s){
System.out.println("Table all ready exists!");
catch (Exception e){
Terms of Agreement:
By using this article, you agree to the following terms...
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame.
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.

This tutorial will show you how to connect to a MySQL database using JSP (JavaServer Pages) under
Windows and Tomcat web server. If you run into problems or find errors, please let me know so I can
fine-tune this document. This document will probably be most useful for those who have done web
scripting with MySQL databases before but would like to get started with JSP/Servlets programming.
Database connectivity provides a good foundation for learning any new language, as you can practice
making real-world applications in a database environment.


1. It is assumed that you already have a MySQL database installed and a table to pull data from.
2. It assumes you understand SQL, and probably have done some web/database scripting with other
3. The author uses the folder C:\Tomcat as the folder where Tomcat will be extracted, however, you
can place the distribution files anywhere you wish.
4. You know the basics of programming Java. If you do not, I highly recommend you check out
Sun's Java Tutorial.

Section A - Installation

1. Install the Java 2 JRE. I put mine in C:\java\jre, which will be used in this tutorial, but you
can put your anywhere you like.
2. Extract the Tomcat distribution files to a folder. The default is jakarta-tomcat-4.1.12, but I
chose to put the files in C:\Tomcat.
3. Copy the MySQL Connector JAR file to the C:\Tomcat\common\lib folder (ie, mysql-

Section B - Environmental Variables

Add the following environmental variables to Windows:

TOMCAT_HOME=C:\TomcatYou can set environmental variables in Windows 2000/XP by going to:
Righy-click My Computer -> Properties -> Advanced -> Environmental Variables

You can set environmental variables in Windows NT 4 by going to:

Righy-click My Computer -> Properties -> Environment

Section C - Working with Tomcat

To start the server, execute startup.bat. To stop the server, execute shutdown.bat in the
C:\Tomcat\bin folder.

By default, the Tomcat web server is access at this URL:


The root folder of the server is located in:


The root and default port can be changed in this file:

You would need the connector J from mysql inorder for the linkage
This is a simple example...

The minmum imports which is needed for a simple application could be:

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

You would then have to create a connection so place this within the class

private Connection sqlConnection;

To test if the driver is properly installed, you could add this function. This is for debugging purposes...

public void testDriver() throws Exception {

System.out.println("Initializing Server... ");
try {
System.out.println(" Driver Found.");
} catch (ClassNotFoundException e) {
System.out.println(" Driver Not Found, exiting..");
throw (e);

And to connect to the database you do this, so then we have a returned the connection from the databases...:

public Connection getConnection(String host, String userDB, String passDB, String database) throws Exception {
String url = "";
try {
url = "jdbc:mysql://" + host + "/" + database;

Connection con = DriverManager.getConnection(url, userDB, passDB);

System.out.println(" Database connection established to " + url+ ".");

return con;
} catch (java.sql.SQLException e) {
System.out.println(" Connection couldn't be established to "+ url);
throw (e);
You can write MySQL applications in a variety of languages. The languages that most people use with MySQL are
PHP and Perl, but a sometimes overlooked option is the MySQL Connector/J driver, which allows you to develop
Java applications that interact with your MySQL server.

MySQL Connector/J works within the framework of the Java JDBC interface, an API that allows Java programs to
use database servers in a portable way. JDBC is based on an approach similar to that used in the design of Perl and
Ruby DBI modules, Python's DB-API module, and PHP's PEAR::DB class. This approach uses a two-tier

• The top level is visible to application programs and presents an abstract interface for connecting to and using
database engines. The application interface does not depend on details specific to particular engines.
• The lower level consists of drivers for individual database engines. Each driver handles the details necessary
to map the abstract application interface onto operations that a specific engine will understand.

The JDBC interface allows developers to write applications that can be used with different databases with a minimum
of porting effort. Once a driver for a given server engine is installed, JDBC applications can communicate with any
server of that type. By using MySQL Connector/J, your Java programs can access MySQL databases.

Note: MySQL Connector/J is the successor to the MM.MySQL driver. If you have JDBC programs written for
MM.MySQL, they should work with MySQL Connector/J as well, although you may want to update the driver class
name used in your programs. Just replace instances of org.gjt.mm.mysql in your Java source files with
com.mysql.jdbc and recompile.

Preliminary Requirements

To use Java applications with MySQL, you may need to install some additional software:

• If you want to compile and run Java programs, you'll need a Java compiler (such as javac or jikes) and a
runtime environment. If these are not already installed on your system, you can get them by obtaining a Java
Software Development Kit (SDK) from java.sun.com.
• If you want only to run precompiled applications, no compiler is necessary, but you'll still need a Java
Runtime Environment (JRE). This too may be obtained from java.sun.com.

This article assumes that you'll write and compile your own programs, and thus that you have a Java SDK installed.
Once you compile a Java program, however, you can deploy it to other machines, even ones that have only a runtime
environment. This works even in heterogenous installations, because Java is platform-independent. Applications
compiled on one platform can be expected to work on other platforms. For example, you can develop on a Linux box
and deploy on Windows.

Connecting to the MySQL Server

To connect to the MySQL server, register the JDBC driver you plan to use, then invoke its getConnection()
method. The following short program, Connect.java, shows how to connect to and disconnect from a server running
on the local host. It accesses a database named test, using a MySQL account with a user name and password of
testuser and testpass:

import java.sql.*;

public class Connect

public static void main (String[] args)
Connection conn = null;

String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
catch (Exception e)
System.err.println ("Cannot connect to database server");
if (conn != null)
conn.close ();
System.out.println ("Database connection terminated");
catch (Exception e) { /* ignore close errors */ }
Compile Connect.java to produce a class file Connect.class that contains executable Java code:
% javac Connect.java
Then invoke the class file as follows and it should connect to and disconnect from your MySQL server:
% java Connect
Database connection established
Database connection terminated
If you have trouble compiling Connect.java, double check that you have a Java Software Development Kit installed
and make sure that the MySQL Connector/J driver is listed in your CLASSPATH environment variable.

The arguments to getConnection() are the connection URL and the user name and password of a MySQL account.
As illustrated by Connect.java, JDBC URLs for MySQL consist of jdbc:mysql:// followed by the name of the
MySQL server host and the database name. An alternate syntax for specifying the user and password is to add them
as parameters to the end of the connection URL:

When you specify a URL using this second format, getConnection() requires only one argument. For example, the
code for connecting to the MySQL server in Connect.java could have been written like this:
String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test?user="
+ userName
+ "&password="
+ password;
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url);
getConnect() returns a Connection object that may be used to interact with MySQL by issuing queries and
retrieving their results. (The next section describes how to do this.) When you're done with the connection, invoke its
close() method to disconnect from the MySQL server.

To increase the portability of your applications, you can store the connection parameters (host, database, user name,
and password) in a Java properties file and read the properties at runtime. Then they need not be listed in the program
itself. This allows you to change the server to which the program connects by editing the properties file, rather than
by having to recompile the program.

Issuing Queries

To process SQL statements in a JDBC-based application, create a Statement object from your Connection object.
Statement objects support an executeUpdate() method for issuing queries that modify the database and return no
result set, and an executeQuery() method for queries that do return a result set. The query-processing examples in
this article use the following table, animal, which contains an integer id column and two string columns, name and


name CHAR(40),
category CHAR(40)
id is an AUTO_INCREMENT column, so MySQL automatically assigns successive values 1, 2, 3, ... as records are added
to the table.

Issuing Queries That Return No Result Set

The following example obtains a Statement object from the Connection object, then uses it to create and populate
the animal table. DROP TABLE, CREATE TABLE, and INSERT all are statements that modify the database, so
executeUpdate() is the appropriate method for issuing them:

Statement s = conn.createStatement ();

int count;
s.executeUpdate ("DROP TABLE IF EXISTS animal");
s.executeUpdate (
"CREATE TABLE animal ("
+ "PRIMARY KEY (id),"
+ "name CHAR(40), category CHAR(40))");
count = s.executeUpdate (
"INSERT INTO animal (name, category)"
+ "('snake', 'reptile'),"
+ "('frog', 'amphibian'),"
+ "('tuna', 'fish'),"
+ "('racoon', 'mammal')");
s.close ();
System.out.println (count + " rows were inserted");
The executeUpdate() method returns the number of rows affected by a query. As shown above, the count is used to
report how many rows the INSERT statement added to the animal table.

A Statement object may be used to issue several queries. When you're done with it, invoke its close() method to
dispose of the object and free any resources associated with it.

Issuing Queries That Return a Result Set

For statements such as SELECT queries that retrieve information from the database, use executeQuery(). After
calling this method, create a ResultSet object and use it to iterate through the rows returned by your query. The
following example shows one way to retrieve the contents of the animal table:

Statement s = conn.createStatement ();

s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
executeQuery() does not return a row count, so if you want to know how many rows a result set contains, you
should count them yourself as you fetch them.

To obtain the column values from each row, invoke getXXX() methods that match the column data types. The
getInt() and getString() methods used in the preceding example return integer and string values. As the example
shows, these methods may be called using the name of a result set column. You can also fetch values by position. For
the result set retrieved by the SELECT query in the example, id, name, and category are at column positions 1, 2 and
3 and thus could have been obtained like this:

int idVal = rs.getInt (1);

String nameVal = rs.getString (2);
String catVal = rs.getString (3);
ResultSet objects, like Statement objects, should be closed when you're done with them.

To check whether or not a column value is NULL, invoke the result set object's wasNull() method after fetching the
value. For example, you could check for a NULL value in the name column like this:

String nameVal = rs.getString ("name");

if (rs.wasNull ())
nameVal = "(no name available)";
Using Placeholders

Sometimes it's necessary to construct queries from values containing characters that require special treatment. For
example, in queries, string values are written enclosed within quotes, but any quote characters in the string itself
should be doubled or escaped with a backslash to avoid creating malformed SQL. In this case, it's much easier to let
JDBC handle the escaping for you, rather than fooling around trying to do so yourself. To use this approach, create a
different kind of statement (a PreparedStatement), and refer to the data values in the query string by means of
placeholder characters. Then tell JDBC to bind the data values to the placeholders and it will handle any special
characters automatically.

Suppose you have two variables nameVal and catVal from which you want to create a new record in the animal
table. To do so without regard to whether or not the values contain special characters, issue the query like this:

PreparedStatement s;
s = conn.prepareStatement (
"INSERT INTO animal (name, category) VALUES(?,?)");
s.setString (1, nameVal);
s.setString (2, catVal);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");
The '?' characters in the query string act as placeholders--special markers indicating where data values should be
placed. The setString() method takes a placeholder position and a string value and binds the value to the
appropriate placeholder, performing any special-character escaping that may be necessary. The method you use to
bind a value depends on the data type. For example, setString() binds string values and setInt() binds integer

Error Handling

If you want to trap errors, execute your JDBC operations within a try block and use an exception handler to display
information about the cause of any problems that occur. JDBC provides getMessage() and getErrorCode()
methods that may be invoked when an exception occurs to obtain the error message and the numeric error code. The
following example deliberately issues a malformed query. When it runs, the executeQuery() method fails and raises
an exception that is handled in the catch block:

Statement s = conn.createStatement ();
s.executeQuery ("XYZ"); // issue invalid query
s.close ();
catch (SQLException e)
System.err.println ("Error message: " + e.getMessage ());
System.err.println ("Error number: " + e.getErrorCode ());