+ All Categories
Home > Documents > JDBC Example With MySQL

JDBC Example With MySQL

Date post: 21-Apr-2015
Category:
Upload: ravi-kant-pandey
View: 262 times
Download: 2 times
Share this document with a friend
118
1 1. Mapping MySQL Data Types in Java 2. Connecting to a MySQL Database in Java 3. Creating a Database in MySQL 4. Creating a Database Table 5. Creating a MySQL Database Table to store Java Types 6. Description of Database Table 7. Deleting a Table from Database 8. Retrieving Tables from a Database 9. Inserting values in MySQL database table 10. Retrieving All Rows from a Database Table 11. Count Rows from a Database Table 12. Getting Column Names from a database table in Java 13. Adding a New Column in Database Table 14. Rename Column Name of a Database Table 15. Make Unique key in a Column 16. Remove Unique Key in Database Table 17. Arranging Records of Database Table in Ascending Order 18. Arranging Records of Database Table in Descending Order 19. Sum of Specific Column Data in a Database Table 20. Deleting All Rows from a Database Table 21. Delete a Specific Row from a Database Table
Transcript
Page 1: JDBC Example With MySQL

1

1. Mapping MySQL Data Types in Java

2. Connecting to a MySQL Database in Java

3. Creating a Database in MySQL

4. Creating a Database Table

5. Creating a MySQL Database Table to store Java Types

6. Description of Database Table

7. Deleting a Table from Database

8. Retrieving Tables from a Database

9. Inserting values in MySQL database table

10. Retrieving All Rows from a Database Table

11. Count Rows from a Database Table

12. Getting Column Names from a database table in Java

13. Adding a New Column in Database Table

14. Rename Column Name of a Database Table

15. Make Unique key in a Column

16. Remove Unique Key in Database Table

17. Arranging Records of Database Table in Ascending Order

18. Arranging Records of Database Table in Descending Order

19. Sum of Specific Column Data in a Database Table

20. Deleting All Rows from a Database Table

21. Delete a Specific Row from a Database Table

Page 2: JDBC Example With MySQL

2

22. Delete a Column from a Database Table

23. Join tables in the specific database

24. Join tables with the NATURAL LEFT JOIN operation

25. Join tables with the NATURAL RIGHT JOIN operation

26. Cross Join Tables in a Specific Database

27. Prepared Statement Set Object

28. Statement Batch Update

29. Prepared Statement Batch Update

30. Select Records Using Prepared Statement

31. Update Records using Prepared Statement

32. Inserting Records using the Prepared Statement

33. Count Records using the Prepared Statement

34. Deleting Records using the Prepared Statement

35. Using the Prepared Statement Twice Time

36. Set Data Types by using Prepared Statement

37. Set byte, short and long data types by using the Prepared Statement

38. Prepared Statement Set Big Decimal

39. Set Date by using the Prepared Statement

40. Set Time by using the Prepared Statement

41. Set Timestamp by using the Prepared Statement

42. Write Text File to Table

43. Copy Table in a MySQL Database

44. Copy One Database Table to Another

Page 3: JDBC Example With MySQL

3

45. Insert Data in Table Using Stored Procedure

46. Inserting Image in Database Table

47. JDBC Mysql Connection String

Page 4: JDBC Example With MySQL

4

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

VARCHAR String

LONGVARCHAR String

NUMERIC java.math.BigDecimal

DECIMAL java.math.BigDecimal

BIT boolean

TINYINT byte

SMALLINT short

INTEGER int

BIGINT long

REAL float

FLOAT double

DOUBLE double

BINARY byte []

VARBINARY byte []

LONGVARBINARY byte []

DATE java.sql.Date

TIME java.sql.Time

TIMESTAMP java.sql.Tiimestamp

Page 5: JDBC Example With MySQL

5

1. CHAR, VARCHAR and LONGVARCHAR 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.

2. NUMERIC and DECIMAL 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 types. 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.

3. BINARY, VARBINARY and LONGVARBINARY 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.

5. TINYINT, SMALLINT, INTEGER and BIGINT 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

Page 6: JDBC Example With MySQL

6

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.

6. REAL, FLOAT and DOUBLE 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.

7. DATE, TIME and TIMESTAMP 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.

Page 7: JDBC Example With MySQL

7

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:

Page 8: JDBC Example With MySQL

8

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();

}

}}

Page 9: JDBC Example With MySQL

9

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:");

Page 10: JDBC Example With MySQL

10

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();

}

}

}

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac CreateDatabase.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java CreateDatabase

Database creation example!

Enter Database name:

RoseIndia

1 row(s) affacted

Page 11: JDBC Example With MySQL

11

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.

Page 12: JDBC Example With MySQL

12

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 varchar(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();

}

}

}

Page 13: JDBC Example With MySQL

13

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, "

Page 14: JDBC Example With MySQL

14

+ "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();

}

}

}

Page 15: JDBC Example With MySQL

15

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:

Page 16: JDBC Example With MySQL

16

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.in));

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");

}

Page 17: JDBC Example With MySQL

17

System.out.println();

} }

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac DiscriptionTable.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java DiscriptionTable

See Description of Table Example!

Enter table name:

vk

Field Type Null Key Default Extra

id int(11) NO

name char(1) YES

Page 18: JDBC Example With MySQL

18

Imagine a situation where we need to delete a table from the database. We can do it very easily

by using the commands in the MySQL database. But how we can delete the table using java

methods and API. In this section we are describing, how to delete a table from database using

java methods. Java provides the facility for deleting a specific table from a given database with

the help of some specified methods. See detailed information given below:

Description of program:

Create a class DeleteTable inside which, firstly establishes the connection with MySQL

database. After establishing the connection we will delete a table from specific database. If the

table which we want to delete get deletes then we will print the message "Table Deletion

process is completely successfully!", otherwise it will display " Table is not exists!".

Description of code:

DROP TABLE table_name:

Above code is used for deleting any table from a given database.

Here is the code of program:

import java.sql.*;

public class DeleteTable{

public static void main(String[] args) {

System.out.println("Tabel Deletion 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();

st.executeUpdate("DROP TABLE Employee1");

System.out.println ("Table Deletion process is completly successfully!");

}

catch(SQLException s){

System.out.println("Table is not exists!");

}

con.close();

}

catch (Exception e){

e.printStackTrace();

}}}

Page 19: JDBC Example With MySQL

19

In database system it is very important to know about the tables. To work with this, it is very

important to know how to retrieve a table and create a table in the database. This section

provides you a facility for retrieving tables from a specific database through an example. In

relational database, all the data is stored in the tabular format (rows and columns). See detail

information below:

Description of program:

In this program we are establishing the connection between the MySQL database and Java

file. We will retrieve the table with the help of some java methods and APIs interface. If the

database has one or more tables then it shows all tables, otherwise displays the message "No

any table in the database".

Description of code:

DatabaseMetaData:

This is an interface of java.sql package that implemented by driver vendors. It tells about the

data of the data like number of tables in the database , the information about the columns of

the table.

getMetaData():

It is a method of Connection interface. This method has metadata around the database and

retrieves DatabaseMetaData object.

ResultSet:

The ResultSet is an interface that provides getter methods (getBoolean, getString, getTable

and so on) for retrieving values. A ResultSet object is by default not updatable and forward

only.

getTables(null, null, "%", types):

This method returns ResultSet and takes the following string types parameter:

catalog : Table catalog name (may be null)

schemaPattern : Table catalog name (may be null)

tableNamePattern : Table name("%")

types : Table type

rs.next():

This method returns the next element of the ResultSet object.getString("Table name"):

Above method retrieves the values from ResultSet object. It takes string type value.

Page 20: JDBC Example With MySQL

20

Here is the code of program:

import java.sql.*;

public class AllTableName{

public static void main(String[] args) {

System.out.println("Listing all table name in Database!");

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);

con = DriverManager.getConnection(url+db, user, pass);

try{

DatabaseMetaData dbm = con.getMetaData();

String[] types = {"TABLE"};

ResultSet rs = dbm.getTables(null,null,"%",types);

System.out.println("Table name:");

while (rs.next()){

String table = rs.getString("TABLE_NAME");

System.out.println(table);

con.close();

}

}

catch (SQLException s){

System.out.println("No any table in the database");

}

}

catch (Exception e){

e.printStackTrace();

}

}}

Page 21: JDBC Example With MySQL

21

Output of program:

C:\vinod\jdbc\jdbc-mysql>javac AllTableName.java

C:\vinod\jdbc\jdbc-mysql>java AllTableName

Listing all table name in Database!

Table name:

employee

employee11

employee2

employee3

employee4

employee5

employee6

employee8

employee9

java_datatypes

java_datatypes2

javatypes

Page 22: JDBC Example With MySQL

22

After making the table in the database, we need to insert the values in the database. Here we

are going to see, how we can insert values in the MySQL database table. We know that tables

store data in rows and column format. After creating a database table, you need to insert the

values in it. In this section, we are providing an example with code that provides the facility

for inserting the values in MySQL database table.

Description of program:

First of all this program establishes the connection with MySQL database through the JDBC

driver, after only that we will be able to insert the values in specific table with the help of some

APIs and methods. If any values get inserted in the table then shows a message "1 row

affected" but if any problems comes while inserting the data in the table then it will displays

the message "SQL statement is not executed!".

Description of code:

INSERT table_name VALUES(field_values):

Above code is used, when you want to insert values in the database table with appropriate

value.

Here is the code of program:

import java.sql.*;

public class InsertValues{

public static void main(String[] args) {

System.out.println("Inserting values in Mysql database table!");

Connection con = null;

String url = "jdbc:mysql://localhost:3306/";

String db = "jdbctutorial";

String driver = "com.mysql.jdbc.Driver";

try{

Class.forName(driver);

con = DriverManager.getConnection(url+db,"root","root");

try{

Statement st = con.createStatement();

int val = st.executeUpdate("INSERT employee VALUES("+13+","+"'Aman'"+")");

System.out.println("1 row affected");

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}}

catch (Exception e){

e.printStackTrace();

Page 23: JDBC Example With MySQL

23

}

}

}

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac InsertValues.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java InsertValues

Inserting values in Mysql database table!

1 row affected

Page 24: JDBC Example With MySQL

24

Here, you will learn how to retrieve all rows from a database table. You know that table

contains the data in rows and columns format. If you want to access the data from a table then

you need to use some APIs and methods. See brief descriptions for retrieving all rows from a

database table as below:

Description of program:

Program establishes the connection between MySQL database and java file so that the we can

retrieve all data from a specific database table. If any exception occurs then shows a message

"SQL code does not execute.".

Description of code:

executeQuery(String sql):

This method executes the SQL statement and returns a single ResultSet object. It takes string

type parameter for executing the SQL statement.

SELECT * FROM table_name:

Above code retrieves all data from specific database table.

getInt(String column_name):

This method is of java.sql.ResultSet interface that takes string type parameter and returns an

integer type values.

getString(String column_name):

This method is same as getInt() method but it returns the string type values.

Here is the code of program:

import java.sql.*;

public class GetAllRows{

public static void main(String[] args) {

System.out.println("Getting All Rows from a table!");

Connection con = null;

String url = "jdbc:mysql://localhost:3306/";

String db = "jdbctutorial";

String driver = "com.mysql.jdbc.Driver";

Page 25: JDBC Example With MySQL

25

String user = "root";

String pass = "root";

try{

Class.forName(driver).newInstance();

con = DriverManager.getConnection(url+db, user, pass);

try{

Statement st = con.createStatement();

ResultSet res = st.executeQuery("SELECT * FROM employee6");

System.out.println("Emp_code: " + "\t" + "Emp_name: ");

while (res.next()) {

int i = res.getInt("Emp_code");

String s = res.getString("Emp_name");

System.out.println(i + "\t\t" + s);

}

con.close();

}

catch (SQLException s){

System.out.println("SQL code does not execute.");

}

}

catch (Exception e){

e.printStackTrace();

}}}

Output of program:

C:\vinod\jdbc\jdbc-mysql>java GetAllRows

Getting All Rows from a table!

Emp_code: Emp_name:

10 vinod

11 Amar

15 Aman

1 sushil

Page 26: JDBC Example With MySQL

26

After creating a database table, if we want to know number of rows in a table then we can get

it very easily by using the simple database query. See brief description below:

Description of program:

For this program to work firstly we need to establish the connection with MySQL database by

the help of JDBC driver. When the connection has been established we need to pass a table

name from the given database in the query and the rows will be counted and the result will be

displayed. If any exception is thrown then it will show "SQL statement is not executed!"

Description of code:

SELECT COUNT(*) FROM table_name;

This code is used to count the rows of given table.

table_name: It is a name of the table of which we want to see the rows.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class CountRows{

public static void main(String[] args) {

System.out.println("Count number of rows in a specific table!");

Connection con = null;

int count = 0;

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 table name:");

String table = bf.readLine();

ResultSet res = st.executeQuery("SELECT COUNT(*) FROM "+table);

while (res.next()){

count = res.getInt(1);

}

System.out.println("Number of column:"+count);

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

Page 27: JDBC Example With MySQL

27

catch (Exception e){

e.printStackTrace();

}

}

}

output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac CountRows.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java CountRows

Count number of rows in a specific table!

Enter table name:

student

Number of column:6

Page 28: JDBC Example With MySQL

28

Here we are providing you an example with code that retrieves all columns name in a specific

database table. Sometimes, you need to know the number of columns and the names of the

columns of the table, so you can retrieve it with the help of this example. See detail

information given below:

Description of program:

Create a class ColumnName. The name of the class should be such that the other person can

easily understand what this program is going to do. Strictly follow the naming conventions of

java. Now declare a static method inside which creates the connection with MySQL database

through the JDBC driver. After establishing the connection then you get all columns name

and number of columns of specified table with the help of some APIs and methods.

Description of code:

ResultSetMetaData:

This is an interface of java.sql package that can be used for getting information about types

and properties of columns in a ResultSet object.

getColumnCount():

Above method retrieves number of columns (integer types data) in the ResultSet object.

getColumnName(int column):

This method returns columns name (string type data) from ResultSetMetaData object and

takes integer type value.

Here is the code of program:

Page 29: JDBC Example With MySQL

29

import java.sql.*;

public class ColumnName{

public static void main(String[] args) {

System.out.println("Getting Column Names Example!");

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);

con = DriverManager.getConnection(url+db, user, pass);

try{

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("SELECT * FROM employee6");

ResultSetMetaData md = rs.getMetaData();

int col = md.getColumnCount();

System.out.println("Number of Column : "+ col);

System.out.println("Columns Name: ");

for (int i = 1; i <= col; i++){

String col_name = md.getColumnName(i);

System.out.println(col_name);

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Page 30: JDBC Example With MySQL

30

Output of program:

C:\vinod\jdbc\jdbc-mysql>javac ColumnName.java

C:\vinod\jdbc\jdbc-mysql>java ColumnName

Getting Column Names Example!

Number of Column : 2

Columns Name:

Emp_code

Emp_name

Page 31: JDBC Example With MySQL

31

In this jdbc tutorial program we are going to learn about adding a new column in database

table. Sometimes it happens that we have created a table and forgets to add some important

column name into it. Later while retrieving the data from that table we come to know that the

table doesn't contains that particular column we are searching for. So there is no need to get

panic. We have the solution for this, we are describing it with the help of the simple example.

Brief description given below:

Description of program:

Firstly we need to create a connection with the help of JDBC driver for connecting to the

MySQL database. Remember, in this program we are going to add columns to an existing

database table. After establishing the connection, it takes table name, column name and it's

data type and at last add a new column in the table. If the column gets inserted or added in the

table then it shows "Query OK, n rows affected" otherwise it will displays a message "Table or

column or data type is not found!".

Description of code:

ALTER TABLE table_name ADD col_name data_type;

Above code is used for adding a new column in the database table and takes appropriate

attributes:

table_name: This is a table name in which you want to add a new column name.

col_name: It is a name of the column that you want to add in a table.

data_type: This is a data type of new column.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class AddColumn{

public static void main(String[] args) {

System.out.println("Adding new column in 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.in));

System.out.println("Enter table name:");

String table = bf.readLine();

Page 32: JDBC Example With MySQL

32

System.out.println("Enter column name:");

String col = bf.readLine();

System.out.println("Enter data type:");

String type = bf.readLine();

int n = st.executeUpdate("ALTER TABLE "+table+" ADD "+col+" "+type);

System.out.println("Query OK, "+n+" rows affected");

}

catch (SQLException s){

System.out.println("Tabel or column or data type is not found!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: Student Table

Stu_id Stu_name Stu_sub

100 vinod computer

101 raju math

102 ranjan bio

103 Aman phy

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac AddColumn.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java AddColumn

Adding new column in table example!

Enter table name:

Student

Enter column name:

Stu_marks

Enter data type:

integer

Query OK, 4 rows affected

Page 33: JDBC Example With MySQL

33

After adding a new column: Student Table

Stu_idl Stu_name Stu_sub Stu_marks

100 vinod computer NULL

101 raju math NULL

102 ranjan bio NULL

103 Aman phy NULL

Page 34: JDBC Example With MySQL

34

This section provides you an example with code for renaming a column name in a database

table. As we know that each table keeps contents in rows and column format. While making a

table we specify the name of each column which we want to add in the table. But later it may

be that we need to change the name of the particular column. So, please don't panic. Here at

roseindia.net, we have the answer of each and every thing. Brief description of the program is

given below:

Description of program:

Firstly this program establishes the connection by using the JDBC driver with the database.

After establishing the connection we will give the table name, old column name which we

want to rename, new column name and it's data type. After that you will see that the column

name has been renamed. If column name gets renamed column then the message we

displaying is "Query OK, n rows affected" and if any problem arises in the SQL statement

then it shows "Wrong entry!".

Description of code:

ALTER TABLE table_name CHANGE old_col new_col data_type:

This query is fired to change the specific column name. It takes appropriate arguments:

table_name: This is a name of the table in which we have to change the column name.

old_col: The old column name that you want to change.

new_col: The new column name

data_type: This is a data type of new column.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class ChangeColumnName{

public static void main(String[] args) {

System.out.println("Change column name in a database 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.in));

System.out.println("Enter table name:");

String table = bf.readLine();

Page 35: JDBC Example With MySQL

35

System.out.println("Enter old column name:");

String old_col = bf.readLine();

System.out.println("Enter new column:");

String new_col = bf.readLine();

System.out.println("Enter data type:");

String type = bf.readLine();

int n = st.executeUpdate

("ALTER TABLE "+table+" CHANGE "+old_col+" "+new_col+" "+type);

System.out.println("Query OK, "+n+" rows affected");

}

catch (SQLException s){

System.out.println("Wrong entry!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: Student

Stu_roll Stu_name Stu_sub

100 vinod computer

101 raju math

102 ranjan bio

103 Aman phy

Page 36: JDBC Example With MySQL

36

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac ChangeColumnName.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java ChangeColumnName

Change column name in a database table example!

Enter table name:

Student

Enter old column name:

Stu_roll

Enter new column:

Stu_id

Enter data type:

integer

Query OK, 4 rows affected

After change the table will look like this

Student Table

Stu_id Stu_name Stu_sub

100 vinod computer

101 raju math

102 ranjan bio

103 Aman phy

Page 37: JDBC Example With MySQL

37

In this section you will learn, how to define a unique key in a column of a database table.

While declaring unique key in a column we should check whether this column is eligible to

store a unique values or not because if the column has been declared as unique then it can't

store a duplicate values. If we ever try to insert the duplicate data in the unique column then

it will show an error message to you that you are trying to insert the duplicate value.

Description of program:

After making a connection with the database firstly compile this program, only after that it

will run, Now give the table name and column name to which you want to make a unique

column. After assigning the unique key to a column the SQL statement is executed with the

help of some java methods. If column name becomes unique then shows "Query OK, n rows

affected." otherwise, displays a message "Table or column is not found!".

Description of code:

ALTER TABLE table_name ADD UNIQUE(col_name):;

Above code is used to make unique of any column . It takes table name and column name.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class MakeUniqueColumn{

public static void main(String[] args) {

System.out.println("Make unique column 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 table name: ");

String table = bf.readLine();

System.out.println("Enter column name that you want to unique values: ");

String col = bf.readLine();

int n = st.executeUpdate("ALTER TABLE "+table+" ADD UNIQUE"+"("+col+")");

System.out.println("Query OK, "+n+" rows affected.");

}

catch (SQLException s){

System.out.println("Table or column is not found!");

}}

Page 38: JDBC Example With MySQL

38

catch (Exception e){

e.printStackTrace();

}}}

Database Table: Student Table

Stu_id Stu_name Stu_sub Stu_marks

100 vinod computer NULL

101 raju math NULL

102 ranjan bio NULL

103 Aman phy NULL

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac MakeUniqueColumn.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java MakeUniqueColumn

Make unique column example!

Enter table name:

Student

Enter column name that you want to unique values:

Stu_id

Query OK, 4 rows affected.

Make unique values: Student Table

Stu_id Stu_name Stu_sub Stu_marks

100 vinod computer NULL

101 raju math NULL

102 ranjan bio NULL

103 Aman phy NULL

Page 39: JDBC Example With MySQL

39

In this section, we will see how to remove unique field of the particular column in a database

table. We know that, any table stores data in the form of rows and columns. In a table we can

have a unique key which can be used to relate the data with the other table. But, what if we

want to remove the unique key from the unique column then those unique values in the

unique column will also gets deletes. By removing the unique key there will be redundancy in

the data.

Description of program:

What this program does in its initial stage is to establish the connection with MySQL database

by using the JDBC drive, only after that it will take a table name and column name from

which we want to remove the unique key. If the unique key gets removes from the column then

it shows "Query OK, n rows affected.". It means, that now this column can have repeated

data.

Description of code:

ALTER TABLE table_name DROP INDEX col_name;

This code is used for removing the unique key from the particular column in the database

table. In this query we will give table and column name from which we to want remove the

unique key.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class RemoveUniqueColumn{

public static void main(String[] args) {

System.out.println("Remove unique column 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 table name: ");

String table = bf.readLine();

System.out.println("Enter column name which has unique values: ");

String col = bf.readLine();

int n = st.executeUpdate("ALTER TABLE "+table+" DROP INDEX "+col);

System.out.println("Query OK, "+n+" rows affected.");

Page 40: JDBC Example With MySQL

40

}

catch (SQLException s){

System.out.println("Table or column is not found!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: Student Table

Stu_id Stu_name Stu_sub Stu_marks

100 vinod computer NULL

101 raju math NULL

102 ranjan bio NULL

103 Aman phy NULL

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac RemoveUniqueColumn.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java RemoveUniqueColumn

Remove unique column example!

Enter table name:

Student

Enter column name which has unique values:

Stu_id

Query OK, 5 rows affected.

Page 41: JDBC Example With MySQL

41

After removing the unique column from Database Table: Student Table

Stu_id Stu_name Stu_sub Stu_marks

100 vinod computer NULL

101 raju math NULL

102 ranjan bio NULL

103 Aman phy NULL

104 manoj che 50

103 Aman phy 85

Page 42: JDBC Example With MySQL

42

This section will provide you the facility for arranging the data of database table in ascending

order. Firstly we should know what is the meaning of ascending order. The ascending order

means an arrangement of data from smallest to largest number in sequence like:

3,6,8,19,21,......... Here we are going to give an example to arrange the data of a column in

ascending order with the help of some java method and APIs. See detailed information below:

Description of program:

Firstly we are going to establish the connection with the MySQL database. After the

connection has been established we need to give a table name and column name which have to

be in ascending order. If data gets arranged in ascending order then shows "Ascending order

of given column:" with it's arranged data and if any problem arises to in this process then

shows a message "SQL statement is not executed!".

Description of code:

SELECT col_name FROM table_name ORDER BY col_name ASC :

This query shows data of a column in ascending order of the specific database table.

The SELECT specifies the table columns that are retrieved.

The FROM clause tells from where the tables has been accessed.

The ORDER BY clause needed to us whenever, we want to sort the data of any column of the

table.

The ASC clause is used to arrange data in ascending order.

It takes column name and table name as its input.

col_name: This is a column name of a table which have to see in the ascending order.

table_name: This is a table name.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class ColumnAscOrder{

public static void main(String[] args) {

System.out.println("Ascending order example!");

Connection con = null;

try{

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

con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/jdbctutorial","root","root");

Page 43: JDBC Example With MySQL

43

try{

Statement st = con.createStatement();

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter table name:");

String table = bf.readLine();

System.out.println("Enter column name which have to see ascending order:");

String col_name = bf.readLine();

ResultSet res = st.executeQuery

("SELECT "+col_name+" FROM "+table+" ORDER BY "+col_name+" ASC");

System.out.println("Ascending order of given column:");

while (res.next()){

int col = res.getInt(1);

System.out.println(col);

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac ColumnAscOrder.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java ColumnAscOrder

Ascending order example!

Enter table name:

emp_sal

Enter column name which have to see ascending order:

Emp_sal

Ascending order of given column:

600

4500

5000

8000

10000

Page 44: JDBC Example With MySQL

44

This section provides an example with code that arrange the records of database table in

descending order. The descending order provides a way for arranging records from largest to

smallest in a sequence like: 100,85,45,12,......... See detail information below:

Description of program:

First of all in this program we are will establish the connection with MySQL database. As

soon as the connection gets established it takes a table name and column name which we want

to see in descending order. If the data gets arranged in descending order then it we are going

to display the message "Descending order of given column:"........... otherwise shows a

message "SQL statement is not executed!".

Description of code:

SELECT col_name FROM table_name ORDER BY col_name DESC:

This query helps us to arrange the records of database table in descending order.

The SELECT specifies the table columns that are retrieved.

The FROM clause tells from where the tables has been accessed.

The ORDER BY clause needed to us whenever, we want to sort the data of any column of the

table.

The DESC clause provides the facility to arrange the data in descending order (decrease

order).

Here is the code of program:

import java.io.*;

import java.sql.*;

public class ColumnDescOrder{

public static void main(String[] args) {

System.out.println("Descending order 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 table name:");

String table = bf.readLine();

System.out.println("Enter column name which have to see descending

order:");

Page 45: JDBC Example With MySQL

45

String col_name = bf.readLine();

ResultSet res = st.executeQuery

("SELECT "+col_name+" FROM "+table+" ORDER BY "+col_name+" DESC");

System.out.println("Descending order of given column:");

while (res.next()){

int col = res.getInt(1);

System.out.println(col);

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac ColumnDescOrder.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java ColumnDescOrder

Descending order example!

Enter table name:

emp_sal

Enter column name which have to see descending order:

Emp_sal

Descending order of given column:

10000

8000

5000

4500

600

Page 46: JDBC Example With MySQL

46

This section describes how we can calculate the sum of specific column data in the database

table. Consider an example of any university where we need to calculate the sum of numbers

achieved by the student. Either we can do it manually or by using just the simple query. By

doing it manually is a very cumbersome work, but by using simple query it can be done very

easily. By seeing the example given below you can easily understand how you can get the sum

of specific column. Here we are providing you an example.

Description of program:

In the program the first task we going to do is to establish the connection with MySQL

database by using the JDBC driver. When the connection has been established pass the table

name and name of that column of which we want to calculate the sum. If the statement gets

processed then it shows the sum of the particular column else it will displays a message "SQL

statement is not executed!".

Description of code:

SELECT SUM(col_name) FROM table_name:

This code can be used to calculate the sum of specific column in database table.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class SumColumn{

public static void main(String[] args) {

System.out.println("Sum of the specific column!");

Connection con = null;

int sum = 0;

String col_name;

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 table name:");

String table = bf.readLine();

System.out.println("Enter column name which have to sum:");

String col = bf.readLine();

ResultSet res = st.executeQuery("SELECT SUM"+"("+col+")"+" FROM "+table);

while (res.next()){

Page 47: JDBC Example With MySQL

47

int c = res.getInt(1);

sum = sum+c;

}

System.out.println("Sum of column = "+sum);

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac SumColumn.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java SumColumn

Sum of the specific column!

Enter table name:

emp_sal

Enter column name which have to sum:

Emp_sal

Sum of column = 28100

Page 48: JDBC Example With MySQL

48

Consider a case where we have been given one database table, now we have to delete all the

rows from the table. This section describes for deleting all rows from a specific database table.

Deleting all rows with the help of some java methods and APIs interfaces that is given below:

Description of program:

This program establishes the connection between the MySQL database and java file with the

help of a jdbc driver. After that deletes all rows by the SQL statement and shows a message

"All rows are completely deleted!". If SQL statement is not executed then displays "SQL

statement is not executed!".

Here is the code of program:

import java.sql.*;

public class DeleteAllRows{

public static void main(String[] args) {

System.out.println

("Example for Deleting All Rows from a database Table!");

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();

String sql = "DELETE FROM employee6";

int delete = st.executeUpdate(sql);

if(delete == 0){

System.out.println("All rows are completelly deleted!");

} }

catch(SQLException s){

System.out.println("SQL statement is not executed!");

} }

catch (Exception e){

e.printStackTrace(); } }}

Page 49: JDBC Example With MySQL

49

Consider a case where we are creating a table and we have to add some data in it. It may

happen that we might add a wrong data in a row, now we need to delete that wrong data. This

can be done very easily, and in this section we are going to do the same that is, how to delete a

specific row from a specific database table. Here is an example with code which provides the

facility for deleting specific row in a database table. Sometimes, you want to delete a specific

row then you use some java methods and APIs interfaces. Detail information given below:

Description of program:

Firstly, in this program we are going to establish the connection by using MySQL database.

After establishing the connection we are going to delete a specific row from the table. If the

row get deletes successfully then it will shows an appropriate message: "Row is deleted.". If

the row doesn't gets deleted then displays a message: "Row is not deleted". If there arises any

problem while establishing the connection or there doesn't exist the table by that name or

there is no data in the table then the exception will be thrown that "SQL statement is not

executed". If any problems occurs while making connection then system displays a message

with the help of java.lang.ClassNotFoundException exception.

Description of code:

DELETE FROM employee6 WHERE Emp_code = '1':

Above code deletes the record in the employee6 table which has Emp_code = '1'.

employee6: This is a table name of a specific database.

Emp_code: It specifies the column name of a specific database table.

'1': This is the value of specified column name.

Here is the code of program:

import java.sql.*;

public class DeleteSpecificRow{

public static void main(String[] args) {

System.out.println("An example for Deleting a Row from a Database!");

Connection con = null;

String url = "jdbc:mysql://localhost:3306/";

String driver = "com.mysql.jdbc.Driver";

String db = "jdbctutorial";

try{

Page 50: JDBC Example With MySQL

50

Class.forName(driver);

con = DriverManager.getConnection(url+db, "root", "root");

try{

Statement st = con.createStatement();

String sql = "DELETE FROM employee6 WHERE Emp_code = '1'";

int delete = st.executeUpdate(sql);

if(delete == 1){

System.out.println("Row is deleted.");

}

else{

System.out.println("Row is not deleted.");

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Page 51: JDBC Example With MySQL

51

In this section, we are going to learn how to delete a column from a database table. We are not

going to create a new table into, and we are expecting that you can make a table yourself. We

are using the already created table in the specific database. Now if we want to delete a column

from a database table then we have been provided with the database query by which we can

do this task very easily. See detailed information below:

Description of program:

The thing which we are going to perform first is to establish the connection by using the

JDBC driver. If any problem is created at the time of connection then it shows

java.lang.ClassNotFoundException exception. After establishing the connection gives a table

name and column name which you want to delete. When column gets deleted then it shows

"Column is deleted successfully". But if SQL statement doesn't get executed then an exception

is thrown and displays a message: "Table or column is not found!".

Description of code:

ALTER TABLE table_name DROP col_name;

This code is used to delete the column form a database table

table_name: This is a table name in which you want to any editing.

col_name: This is a column name which have to deleted.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class DeleteColumn{

public static void main(String[] args) {

System.out.println("Delete columns 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 table name: ");

String table = bf.readLine();

System.out.println("Enter column name: ");

String col = bf.readLine();

st.executeUpdate("ALTER TABLE "+table+" DROP "+col);

System.out.println("Column is deleted successfully!");

Page 52: JDBC Example With MySQL

52

}

catch (SQLException s){

System.out.println("Table or column is not found!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: Student Table

Stu_roll Stu_name Stu_sub Stu_marks

100 vinod computer 95

101 raju math 89

102 ranjan bio 80

103 Aman phy 85

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac DeleteColumn.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java DeleteColumn

Delete columns example!

Enter table name:

Student

Enter column name:

Stu_marks

Column is deleted successfully!

Page 53: JDBC Example With MySQL

53

After deleting a column:

Student Table

Stu_roll Stu_name Stu_sub

100 vinod computer

101 raju math

102 ranjan bio

103 Aman phy

Page 54: JDBC Example With MySQL

54

Consider a case, where there is too many records and tables in a database. Now to retrieve a

particular row from a table or database is a very time consuming. So, what the alternative to

that, divide the table in more than one table. In this section, we are going to see how to join

two or more tables in a specific database. For this you need to have two or more table in the

database. If two or more tables are available in the database then Join operation is performed

otherwise not. Firstly, it is important to know about the join operation. Join operation provides

the facility to combine records between two or more tables. It relates one table to another.

Joining is the type of query for retrieving data two or more table in specific database. You can

join the tables various types like: Natural join, Natural left join, Natural right join and so on.

Here we are providing you an example with code that joins two tables through the NATURAL

JOIN. Brief information given below:

Join: A join provides the facility to connect two tables are merged to each other according to

field that is common and creates a new virtual table.

NATURAL JOIN: It is a type of join that retrieves data within specified tables to specific field

is matched.

NATURAL LEFT JOIN: In this operation both tables are merged to each other according to

common fields but the priority is given to the first table in database.

NATURAL RIGHT JOIN: It also same as Natural left join but it retrieves the data from the

second table in the database.

Description of program:

First of all, this program establishes the connection with MySQL database through the JDBC

driver. After establishing the connection the NATURAL JOIN operation is performed within

two tables say: employee and Emp_sal. The employee table holds the Emp_ed and Emp_name

fields and Emp_sal table contains the Emp_name and Emp_sal. We are making use of the

emp_name to join the tables.

Description of code:

SELECT *FROM employee NATURAL JOIN Emp_sal:

This code is used to show all fields that matches in the both tables on the basis of Emp_name

field.

Page 55: JDBC Example With MySQL

55

Here is the code of program:

import java.sql.*;

public class NatJoinTable{

public static void main(String[] args) {

System.out.println("Natural Join Tables 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();

ResultSet res = st.executeQuery

("SELECT *FROM "+"employee"+" NATURAL JOIN "+"Emp_sal"); //Join two tables

System.out.println("Emp_name" + "\t" + "Emp_ed" + "\t" + "Emp_sal");

while(res.next()){

String name = res.getString("Emp_name");

int ed = res.getInt("Emp_ed");

int sal = res.getInt("Emp_sal");

System.out.println(name + "\t\t" + ed + "\t" + sal);

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Download this example.

Table:- employee:

Emp_ed Emp_name

2

10

13

santosh

deepak

Aman

Page 56: JDBC Example With MySQL

56

Table:- Emp_sal:

Emp_name Emp_sal

Aman

santosh

8000

4500

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac NatJoinTable.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java NatJoinTable

Natural Join Tables Example!

Emp_name Emp_ed Emp_sal

santosh 2 4500

Aman 13 8000

Page 57: JDBC Example With MySQL

57

This section describes the NATURAL LEFT JOIN operation and how to retrieve data through

it. In this operation we are going to retrieve data according to match the field name of another

tables.

NATURAL LEFT JOIN: In this operation both tables are merged to each other according to

common fields but the priority is given to the first table in database.

Description of program:

In this program we are going to establish the connection with MySQL database by using the

JDBC driver, after that we will join two tables through the help of NATURAL LEFT JOIN

operation. It retrieves data on the specific field name that matches in both tables.

Description of code:

SELECT *FROM employee NATURAL LEFT JOIN Emp_sal:

Above code retrieves all data that matches in both tables on the basis of Emp_name field.

Here is the code of program:

import java.sql.*;

public class NatLeftJoinTable{

public static void main(String[] args) {

System.out.println("Natural Left Join Tables 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();

ResultSet res = st.executeQuery

("SELECT *FROM "+"employee"+" NATURAL LEFT JOIN "+"Emp_sal");

//Natural Left Join two tables

System.out.println("Emp_name" + "\t" + "Emp_ed" + "\t" + "Emp_sal");

while(res.next()){

Page 58: JDBC Example With MySQL

58

String name = res.getString("Emp_name");

int ed = res.getInt("Emp_ed");

int sal = res.getInt("Emp_sal");

System.out.println(name + "\t\t" + ed + "\t" + sal);

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Table:- employee:

Emp_ed Emp_name

2

10

13

santosh

deepak

Aman

Table:- Emp_sal:

Emp_name Emp_sal

Aman

santosh

8000

4500

Page 59: JDBC Example With MySQL

59

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac NatLeftJoinTable.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java NatLeftJoinTable

Natural Left Join Tables Example!

Emp_name Emp_ed Emp_sal

santosh 2 4500

deepak 10 0

Aman 13 8000

Page 60: JDBC Example With MySQL

60

This section describes the NATURAL RIGHT JOIN operation of table in a specific database.

This operation join tables on the basis of matching fields but priority will be given to the right

table field values. Here we are providing you an example with code to join the tables through

the NATURAL RIGHT JOIN operation. See detail information given below:

NATURAL RIGHT JOIN: It also same as Natural left join but it retrieves the data from the

second table in the database.

Description of program:

Firstly, this program establishes connection with MySQL database through the JDBC driver.

After establishing the connection the NATURAL RIGHT JOIN operation is performed and

join tables. Program has two tables: employee and Emp_sal. Both tables have some fields and

join tables on the basis of matching field. Here we will see for joining the tables with

Emp_name filed's values and priority to second table (Emp_sal).

Description of code:

SELECT *FROM employee NATURAL RIGHT JOIN Emp_sal:

This code is used to retrieve data from both tables that is matching on the tables field. In

NATURAL RIGHT JOIN operation join tables to priority of second table.

Here is the code of program:

import java.sql.*;

public class NatRightJoinTable{

public static void main(String[] args) {

System.out.println("Natural Right Join Tables 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();

ResultSet res = st.executeQuery

("SELECT *FROM "+"employee"+" NATURAL RIGHT JOIN "+"Emp_sal");

//Natural Right Join two tables

System.out.println("Emp_name" + "\t" + "Emp_ed" + "\t" + "Emp_sal");

while(res.next()){

String name = res.getString("Emp_name");

int ed = res.getInt("Emp_ed");

int sal = res.getInt("Emp_sal");

Page 61: JDBC Example With MySQL

61

System.out.println(name + "\t\t" + ed + "\t" + sal);

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Download this example.

Table:- employee:

Emp_ed Emp_name

2

10

13

santosh

deepak

Aman

Table:- Emp_sal:

Emp_name Emp_sal

Aman

santosh

8000

4500

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac NatRightJoinTable.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java NatRightJoinTable

Natural Right Join Tables Example!

Emp_name Emp_ed Emp_sal

Aman 13 8000

santosh 2 4500

Page 62: JDBC Example With MySQL

62

This section introduces you to the cross join between two tables. The cross join operation

retrieves data between two tables as a Cartesian product of set theory in mathematics. Each

row will get multiplied by other rows. If one table has three rows and the second row has two

rows, then the cartesian of two table will be six. See brief description below:

Cross Join: This is a type of join table operation. It is a same as inner and outer join

operation. The cross join is used to retrieve data from tables as Cartesian product format of set

theory in mathematics. All rows are shown to be multiply by to another tables' rows.

Description of program:

First of all this program establishes the connection, after that the cross join operation will be

performed between two tables. Both tables hold some specific fields and it's values. While you

retrieve data in cross join format, it shows that the each row will get multiply by other rows.

Description of code:

SELECT *FROM employee, Emp_sal :

This code is used to retrieve data form both tables as Cartesian product format (multiply the

field to each other).

Here is the code of program:

import java.sql.*;

public class CrossJoinTable{

public static void main(String[] args) {

System.out.println("Natural Left Join Tables 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();

ResultSet res = st.executeQuery

("SELECT *FROM "+"employee"+","+"Emp_sal"); //Cross Join two tables

System.out.println("Emp_name" + "\t" + "Emp_ed" + "\t" + "Emp_sal");

while(res.next()){

String name = res.getString("Emp_name");

int ed = res.getInt("Emp_ed");

int sal = res.getInt("Emp_sal");

System.out.println(name + "\t\t" + ed + "\t" + sal);

}

Page 63: JDBC Example With MySQL

63

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Table:- employee:

Emp_ed Emp_name

2

10

13

santosh

deepak

Aman

Table:- Emp_sal:

Emp_name Emp_sal

Aman

santosh

8000

4500

Output of program:

C:\vinod\jdbc\jdbc\jdbc-mysql>javac CrossJoinTable.java

C:\vinod\jdbc\jdbc\jdbc-mysql>java CrossJoinTable

Natural Left Join Tables Example!

Emp_name Emp_ed Emp_sal

santosh 2 8000

santosh 2 4500

deepak 10 8000

deepak 10 4500

Aman 13 8000

Aman 13 4500

Page 64: JDBC Example With MySQL

64

In JDBC tutorial we are going to learn about the PreparedStatement and how to use with

setObject method.

PreparedStatement: This is an interface of java.sql package which extends Statement

interface. If you want to execute Statement object many times then we should use

PreparedStatement object as it reduces the execution time. PreparedStatement object is faster

than the Statement object as it is precompiled. In PreparedStatement we use IN parameter

whose values are not known when the Sql statement is created. So we use "?" as a IN

parameter and we also know it by the name of parameter marker. In this interface the

modification has been done on the methods execute, executeQuery and executeUpdate. These

methods are modified in such a way so that they take no argument.

Description of program:

In this program we are going to insert data in the database by using the setObject method of

PreparedStatement interface. Before going into the details of the program we should firstly

need to establish the connection with MySQL database by the help of JDBC driver. After

establishing the connection now we will insert the data in setObject method. If the data gets

added in the database table then it will display a message "Record is added in the table."

otherwise it will show "SQL statement is not executed!".

Description of code:

prepareStatement(String sql):

This method returns the PreparedStatement object for sending the parameterized SQL

statement to the database that contains the pre-compiled SQL statement. Here the pre-

compiled means once the statement has been compiled then it will not compile the same thing

again. It takes the string type arguments which contains one or more '?' parameter

placeholders.

setObject(int par_index, object obj):

It is used for setting the values of parameterized index by using the given object in this

method. It takes two arguments to given below:

par_index: It specifies the parameter like: the first is 1, second is 2, ......

object obj: It contains the parameter values to given by the users.

Page 65: JDBC Example With MySQL

65

Here is the code of program:

import java.sql.*;

public class PreparedStatementSetObject{

public static void main(String[] args) {

System.out.println("Prepared Statement Set Array Example!");

Connection con = null;

try{

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

con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/jdbctutorial","root","root");

try{

PreparedStatement prest = con.prepareStatement("insert emp_sal

values(?,?)");

prest.setObject(1,"Sushil");

prest.setObject(2,15000);

int n = prest.executeUpdate();

System.out.println(n + " Record is added in the table.");

con.close();

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: emp_sal

Emp_name Emp_sal

ghtdfgl 5455

Raja Ram 545

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac PreparedStatementSetObject.java

C:\vinod\jdbc\jdbc\PreparedStatement>java PreparedStatementSetObject

Prepared Statement Set Array Example!

1 Record is added in the table.

Page 66: JDBC Example With MySQL

66

After executing the program:

Database Table: emp_sal

Emp_name Emp_sal

ghtdfgl 5455

Raja Ram 545

Sushil 15000

Page 67: JDBC Example With MySQL

67

In this section we are going to learn about the batch update and how to use it. Here, we are

providing an example with code to execute the statement in a batch. Batch updates means

more than one statements are executed or updates simultaneously in the database. In this

process multiple SQL queries are added in the Statement object and update the records of

database simultaneously. It is the new feature of JDBC 2.0 core API. See detailed description

below:

Description of program:

In this program we are going to execute the multiple queries at a time. Firstly we are going to

establish the connection with MySQL database by using the JDBC driver. When the

connection has been established with the database then we will execute multiple SQL

statement in a batch for updating the records. This program performs inserting and deleting

the data in given tables. If both processes gets executed then it shows a message

"Successfully!" and if any problem arises in the batch update then the exception will be

thrown BatchUpdateException which shows a message "SQL statement is not executed!".

Description of code:

setAutoCommit(boolean bol):

This method is used for setting the connection to auto-commit mode. If we are using false

parameter in this method then the will not be added in the database until we call commit

explicitly. By default auto-commit mode value is true.

addBatch(String table):

This method adds the given SQL statement with the Statement object. It takes String type

arguments like SQL queries.

executeBatch():

This method is used to execute the multiple commands in the database simultaneously. If it

executes successfully then returns integer type array.

commit():

If the auto-commit mode is disable then we this method provides the facility to commit all

changes in the database.

Page 68: JDBC Example With MySQL

68

Here is the code of program:

simport java.sql.*;

public class StatementBatchUpdate{

public static void main(String[] args) {

System.out.println("Prepared Statement Batch Update example!");

Connection con = null;

try{

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

con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/jdbctutorial","root","root");

try{

con.setAutoCommit(false);

String table1 = "INSERT emp_sal VALUES('vikash1',1200)";

String table2 = "DELETE FROM movies WHERE title = 'raja'";

Statement st = con.createStatement();

st.addBatch(table1);

st.addBatch(table2);

int count[] = st.executeBatch();

con.commit();

con.close();

System.out.println("Successfully!");

}

catch (BatchUpdateException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Page 69: JDBC Example With MySQL

69

This section helps to use the PreparedStatement with BatchUpdate and we are going to

provide an example that performs batch update facility. In batch update more than one

records can be added in the database simultaneously by using the some java methods like:

addBatch and executeUpdate.

First of all we are going to describe the Batch Update. A batch update is a collection of

multiple update statements that provides the facility for submitting in the database as a batch.

Description of program:

In this program firstly we have to establish the connection with MySQL database by using the

JDBC driver. When the connection has been established we need to give the query in the

prepareStatement method and it returns PreparedStatement object. The data is submitted in a

batch by the addBatch method and updates it by using the executeBatch method of the

PreparedStatement interface. If all records will get added in the database then it will display a

message "Added Successfully!" and if any problem arises then it throws an

BatchUpdateException and it shows "SQL statement is not executed!".

Here is the code of program:

import java.sql.*;

public class PreparedStatementBatchUpdate{

public static void main(String[] args) {

System.out.println("Prepared Statement Batch Update Example!");

Connection con = null;

try{

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

con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/jdbctutorial","root","root");

try{

con.setAutoCommit(false);

String sql = "INSERT movies VALUES(?,?)";

PreparedStatement prest = con.prepareStatement(sql);

prest.setString(1,"Bagal bali");

prest.setInt(2,2002);

prest.addBatch();

Page 70: JDBC Example With MySQL

70

prest.setString(1,"Raja Hindustani");

prest.setInt(2,1998);

prest.addBatch();

prest.setString(1,"Diwar");

prest.setInt(2,1980);

prest.addBatch();

prest.setString(1,"Nadia ke par");

prest.setInt(2,1975);

prest.addBatch();

int count[] = prest.executeBatch();

con.commit();

con.close();

System.out.println("Added Successfully!");

}

catch (BatchUpdateException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: movies

title year_made

alam ara 1945

Karan 2005

Karan 2005

Page 71: JDBC Example With MySQL

71

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac PreparedStatementBatchUpdate.java

C:\vinod\jdbc\jdbc\PreparedStatement>java PreparedStatementBatchUpdate

Prepared Statement Batch Update Example!

Added Successfully!

After executing the program:

Database Table: movies

title year_made

alam ara 1945

Karan 2005

Karan 2005

Bagal bali 2002

Raja Hindistani 1998

Diwar 1980

Nadia ke par 1975

Page 72: JDBC Example With MySQL

72

In this section we will learn how to select some specific records by using the

PreparedStatement. We know that the PreparedStatement object represents a precompiled

SQL statement. See brief information below:

Description of program:

In this program firstly we need to establish the connection with MySQL database by using the

JDBC driver. After establishing the connection we pass the necessary SQL query in the

prepareStatement method. This method returns the PreparedStatement object. According to

the conditions given in the query the result will be displayed to the user. Here we are

displaying all records between 1980 and 2004 in the movies database table and it displays the

number of records that follows this conditions. If any problems arises in that process it shows

a message "SQL statement is not executed!".

Here is the code of program:

import java.sql.*;

public class SelectRecords{

public static void main(String[] args) {

System.out.println("Select Records Example by using the Prepared

Statement!");

Connection con = null;

int count = 0;

try{

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

con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/jdbctutorial","root","root");

try{

String sql

= "SELECT title,year_made FROM movies WHERE year_made >= ? AND year_made <=

?";

PreparedStatement prest = con.prepareStatement(sql);

prest.setInt(1,1980);

prest.setInt(2,2004);

ResultSet rs = prest.executeQuery();

while (rs.next()){

String mov_name = rs.getString(1);

int mov_year = rs.getInt(2);

count++;

System.out.println(mov_name + "\t" + "- " + mov_year);

}

System.out.println("Number of records: " + count);

prest.close();

con.close();

}

Page 73: JDBC Example With MySQL

73

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: movies

title year_made

alam ara 1945

Karan 2005

Karan 2005

Bagal bali 2002

Raja Hindistani 1998

Diwar 1980

Nadia ke par 1975

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac SelectRecords.java

C:\vinod\jdbc\jdbc\PreparedStatement>java SelectRecords

Select Records Example by using the Prepared Statement!

Bagal bali - 2002

Raja Hindustani - 1998

Diwar - 1980

Number of records: 3

Page 74: JDBC Example With MySQL

74

The JDBC provides you the facility for updating the records. In this JDBC tutorial we are

going to learn about the process of updating the records by using the

PreparedStatement. Here arise a question, what is updating the records. In the case of

relational database management system (RDBMS) we use the SQL "UPDATE" statement for

updating the data in one or more records. See brief description below:

Description of program:

In this program we are going to establish the connection with MySQL database by using the

JDBC driver. When the connection has been established then we pass a SQL statement with

some conditions in it for selecting the specific records and pass this query in the

prepareStatement method. This method returns an object of PreparedStatement. If the query

gets executed then give a message "Updating Successfully!" otherwise it displays "SQL

statement is not executed!".

Here is the code of program:

import java.sql.*;

public class UpdatesRecords{

public static void main(String[] args) {

System.out.println("Updates Records Example through Prepared Statement!");

Connection con = null;

try{

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

con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/jdbctutorial","root","root");

try{

String sql = "UPDATE movies SET title = ? WHERE year_made = ?";

PreparedStatement prest = con.prepareStatement(sql);

prest.setString(1,"Sanam We wafafa");

prest.setInt(2,2005);

prest.executeUpdate();

System.out.println("Updating Successfully!");

con.close();

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}}}

Page 75: JDBC Example With MySQL

75

Database Table: movies

title year_made

alam ara 1945

Karan 2005

Karan 2005

Bagal bali 2002

Raja Hindistani 1998

Diwar 1980

Nadia ke par 1975

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac UpdatesRecords.java

C:\vinod\jdbc\jdbc\PreparedStatement>java UpdatesRecords

Updates Records Example through Prepared Statement!

Updating Successfully!

Page 76: JDBC Example With MySQL

76

After executing the program:

Database Table: movies

title year_made

alam ara 1945

Sanam We wafafa 2005

Sanam We wafafa 2005

Bagal bali 2002

Raja Hindistani 1998

Diwar 1980

Nadia ke par 1975

Page 77: JDBC Example With MySQL

77

In this section we are going to learn how we will insert the records in the database table by

using the PreparedStatement interface of java.sql package. As we all know that in database

all records are added in the table in a tabular format like: rows and columns. See brief

description below:

Description of program:

This program will perform the work for inserting the records in 'movies' database table. For

this, first of all we need to establish the connection with MySQL database by using the JDBC

driver. When the connection has been established then we will pass a SQL statement in the

prepareStatement that returns the PreparedStatement object. After setting the values of movie

name and release year the values are inserted in the movies table by the help of executeUpdate

method then it will show a message "row(s) affected" otherwise display "SQL statement is not

executed!" . The executeUpdate method also executes the SQL statement (INSERT, UPDATE,

DELETE) at the time of inserting, updating and deleting the records from the database table.

Here is the code of program:

import java.io.*;

import java.sql.*;

public class InsertRecords{

public static void main(String[] args) {

System.out.println("Insert records example using prepared statement!");

Connection con = null;

try{

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

con = DriverManager.getConnection("jdbc:mysql:

//localhost:3306/jdbctutorial","root","root");

try{

String sql = "INSERT movies VALUES(?,?)";

PreparedStatement prest = con.prepareStatement(sql);

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter movie name:");

String mov = bf.readLine();

prest.setString(1, mov);

System.out.println("Enter releases year of movie:");

int year = Integer.parseInt(bf.readLine());

prest.setInt(2, year);

int count = prest.executeUpdate();

System.out.println(count + "row(s) affected");

con.close();

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

Page 78: JDBC Example With MySQL

78

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: movies

title year_made

alam ara 1945

Bagal bali 2002

Diwar 1980

Nadia ke par 1975

Karan 1996

Ramayan 1966

Yarana 1988

Muhabte 1998

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac InsertRecords.java

C:\vinod\jdbc\jdbc\PreparedStatement>java InsertRecords

Insert records example using prepared statement!

Enter movie name:

Bagban

Enter releases year of movie:

2003

1row(s) affected

Page 79: JDBC Example With MySQL

79

After executing the program:

Database table: movies table

title year_made

alam ara 1945

Bagal bali 2002

Diwar 1980

Nadia ke par 1975

Karan 1996

Ramayan 1966

Yarana 1988

Muhabte 1998

Bagban 2003

Page 80: JDBC Example With MySQL

80

In this section we will learn how to count all records of the database table by using the

PreparedStatement interface of java.sql package. As we know that table keeps the records in

tabular format like: rows and columns. A table has one or more records. If you will know that

how many records in a database table then you get easily with the help of given program in

RoseIndia.Net JDBC tutorial. See detailed information below:

Description of program:

This program helps us for counting the records of database table by using the

PreparedStatement. For this, firstly we will establish the connection with MySQL database by

using the JDBC driver. When connection has been established it takes a table name of

database, only after that it will count the records of database table with the help of

executeQuery method that returns a single ResultSet object and displays the number of

records, otherwise it will show the message "SQL statement is not executed!".

Here is the code of program:

import java.io.*;

import java.sql.*;

public class CountRecords{

public static void main(String[] args) {

System.out.println("Count records example using prepared statement!");

Connection con = null;

int records = 0;

try{

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

con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/jdbctutorial","root","root");

try{

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter table name:");

String table = bf.readLine();

String sql = "SELECT COUNT(*) FROM "+table;

PreparedStatement prest = con.prepareStatement(sql);

ResultSet rs = prest.executeQuery();

while (rs.next()){

records = rs.getInt(1);

}

System.out.println("Number of records: " + records);

con.close();

}

catch (SQLException s){

System.out.println("Table does not exist in the database!");

}

}

Page 81: JDBC Example With MySQL

81

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: movies

title year_made

alam ara 1945

Sanam We wafafa 2005

Sanam We wafafa 2005

Bagal bali 2002

Diwar 1980

Nadia ke par 1975

Karan 1996

Ramayan 1966

Yarana 1988

Muhabte 1998

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac CountRecords.java

C:\vinod\jdbc\jdbc\PreparedStatement>java CountRecords

Count records example using prepared statement!

Enter table name:

movies

Number of records: 10

Page 82: JDBC Example With MySQL

82

This section helps us for deleting the records from the database table by using the

PreparedStatement interface of the java.sql package. Sometimes, some records we have

entered becomes useless after sometime so we need to delete those records. We can do it very

easily by using the simple Sql query. The given example provides the facility for deleting the

records from the database table. Brief description below: Please go through this example very

carefully.

Description of program:

In this program we are going to delete the records from the 'movies' table that released in the

year 1985. For this, first of all we will establish the connection with MySQL database by using

the JDBC driver. After establishing the connection we will pass the SQL statement in the

prepareStatemet method which returns the PreparedStatement object and we will set the

releases year of movies in the setInt method by using the PreparedStatement object. If it

records gets delete then the executeUpdate method will return the number of deleted records.

This method will execute the SQL statement that may be INSERT, UPDATE or DELETE

statement. If any problems arises with SQL statement then it will display a message "SQL

statement is not executed!".

Here is the code of program:

import java.sql.*;

public class DeleteRecords{

public static void main(String[] args) {

System.out.println("Delete records example using prepared statement!");

Connection con = null;

try{

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

con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/jdbctutorial","root","root");

try{

String sql = "DELETE FROM movies where year_made = ?";

PreparedStatement prest = con.prepareStatement(sql);

prest.setInt(1,1985);

int del = prest.executeUpdate();

System.out.println("Number of deleted records: " + del);

con.close();

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

} }

catch (Exception e){

e.printStackTrace();

}}}

Page 83: JDBC Example With MySQL

83

Database Table: movies

title year_made

alam ara 1945

Bagal bali 2002

Karan 1996

Bagban 2003

Kuch kuch hota hi 1985

Ham hi tumahare sanam 1985

Output of the program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac DeleteRecords.java

C:\vinod\jdbc\jdbc\PreparedStatement>java DeleteRecords

Delete records example using prepared statement!

Number of deleted records: 2

After executing the program:

Database Table: movies

title year_made

alam ara 1945

Bagal bali 2002

Karan 1996

Bagban 2003

Page 84: JDBC Example With MySQL

84

This JDBC tutorial helps us to use the PreparedStatement interface of java.sql package twice

in a program. According to our requirement we can use the PreparedStatement object. The

PreparedStatement object represents the precompiled SQL statement. Whenever, the SQL

statement is precompiled then it stored in the PreparedStatement object which executes the

statement many times and it reduces the time duration of execution. The PreparedStatement

uses the '?' with SQL statement that provides the facility for setting an appropriate conditions

in it. See brief description below:

Description of program:

In this program we are going to retrieve the movies name and it releases year from the

'movies' database table which releases in the year 2002 and 2003 by using the

PreparedStatement object. For this to work, first of all we will establish the connection with

MySQL database by using the JDBC driver. When the connection has been established then

we will pass the SQL statement with some conditions in the prepareStatement method that

returns the PreparedStatement object, after this only we will get the result according to our

requirements. If any problem arises in this then it will display a message "SQL statement is

not executed!".

Here is the code program:

import java.sql.*;

public class TwicePreparedStatement{

public static void main(String[] args) {

System.out.println("Twice use prepared statement example!\n");

Connection con = null;

PreparedStatement prest;

try{

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

con = DriverManager.getConnection("jdbc:mysql:

//localhost:3306/jdbctutorial","root","root");

try{

String sql = "SELECT * FROM movies WHERE year_made = ?";

prest = con.prepareStatement(sql);

prest.setInt(1,2002);

ResultSet rs1 = prest.executeQuery();

Page 85: JDBC Example With MySQL

85

System.out.println("List of movies that made in year 2002");

while (rs1.next()){

String mov_name = rs1.getString(1);

int mad_year = rs1.getInt(2);

System.out.println(mov_name + "\t- " + mad_year);

}

prest.setInt(1,2003);

ResultSet rs2 = prest.executeQuery();

System.out.println("List of movies that made in year 2003");

while (rs2.next()){

String mov_name = rs2.getString(1);

int mad_year = rs2.getInt(2);

System.out.println(mov_name + "\t- " + mad_year);

}

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: movies

title year_made

alam ara 1945

Bagal bali 2002

Karan 1996

Bagban 2003

Ram Teri Ganga Maili 2003

Page 86: JDBC Example With MySQL

86

output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac TwicePreparedStatement.java

C:\vinod\jdbc\jdbc\PreparedStatement>java TwicePreparedStatement

Twice use prepared statement example!

List of movies that made in year 2002

Bagal bali - 2002

List of movies that made in year 2003

Bagban - 2003

Ram Teri Ganga Maili - 2003

Page 87: JDBC Example With MySQL

87

In this section we are going to learn the method for setting data types (String, int, float and

double) in the PreparedStatement interface of java.sql package. We know that the data types of

MySQL and java programming language are not same but we need some mechanism for

transferring the data to each other Java and MySQL. Mapping between both java and MySQL

provides the facility for supporting each data types like:

Java data type MySQL data type

int integer (INTEGER)

double double, float (DOUBLE, FLOAT)

float real (REAL)

Description of program:

Here, we are going to set some java data types by using the PreparedStatement with the help of

this program. The program first of all establishes the connection with MySQL database

through the JDBC driver. After establishing a connection the prepareStatement takes SQL

query statement and then returns the PreparedStatement object. Now, we will set all data

types like String, int, double and float by using some methods like: setString, setInt, setDouble

and setFloat method. These methods set the data in the database table (student) individually

according to it's nature that is supported by both java and MySQL. Data is then added in the

database table (student) that can be seen in a message as "row(s) affected" otherwise a display

phrase as "SQL statement is not executed!".

Here is the code of program:

import java.sql.*;

public class SetDataTypes{

public static void main(String[] args) {

System.out.println("Set string,ingeger,double

and float example by using the Prepared Statement!");

Connection con = null;

try{

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

con = DriverManager.getConnection("jdbc:mysql:

//localhost:3306/jdbctutorial","root","root");

try{

String sql = "INSERT student VALUES(?,?,?,?)";

Page 88: JDBC Example With MySQL

88

PreparedStatement prest = con.prepareStatement(sql);

prest.setString(1,"deepak");

prest.setInt(2,95);

prest.setDouble(3,32.50);

prest.setFloat(4,41.52f);

int row = prest.executeUpdate();

System.out.println(row + " row(s) affected)");

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

} }}

Database Table: student

Stu_name Stu_marks Stu_ave Stu_total

raju (NULL) (NULL) (NULL)

virendra 86 35.255 56.05

deepak 95 32.5 41.52

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac SetDataTypes.java

C:\vinod\jdbc\jdbc\PreparedStatement>java SetDataTypes

Set string,ingeger,double and float example by using the Prepared Statement!

1 row(s) affected)

Page 89: JDBC Example With MySQL

89

After executing the program:

Database Table: student

Stu_name Stu_marks Stu_ave Stu_total

raju (NULL) (NULL) (NULL)

virendra 86 35.255 56.05

deepak 95 32.5 41.52

vinod 86 47.52 65.025

Page 90: JDBC Example With MySQL

90

This tutorial teaches you the process of setting the byte, short and long data types in the

PreparedStatement interface of the java.sql package. We know that the java and MySQL data

types could not be same. But mapping is a mechanism to provide the facility for transferring

the data to each other. For better understanding see the mapping between java and MySQL in

the following explanation.

Java data type MySQL data type

byte tinyint (TINYINT)

short smallint (SMALLINT)

long bigint (BIGINT)

Description of program:

With the help of this program we are going to insert the byte, short and long data types in

'datatypes' table through the PreparedStatement interface of java.sql package. First of all,

establish the connection with MySQL database by using the JDBC driver. After establishing

the connection, it takes the SQL query in the prepareStatement and returns the

PreparedStatement object. Now, we will insert different types of data like: byte, short and long

by using the setByte, setShort and setLong methods. You will get the inserted data in the

database table with a message "row(s) affected" otherwise it will display "SQL statement is

not executed!".

Description of code:

setByte(int index, byte b):

This method takes two arguments: integer and byte types. The integer type data defines the

index and other takes bytes. It sets the arguments to the java byte value. When it sends the into

the database then the JDBC driver switch over this into the SQL TINYINT value.

setShort(int index, short s):

Above method sets the arguments to java short value. When it sends the data into database

then the JDBC driver switch to SQL SMALLINT value. It also takes two types arguments like:

integer and short.

setLong(int index, long l):

The method used for setting the arguments to java long value. It takes integer and long types

data. The JDBC driver sends the data into database to SQL BIGINT value.

Page 91: JDBC Example With MySQL

91

Here is the code of program:

import java.sql.*;

public class SetByteSortLong{

public static void main(String[] args) {

System.out.println("Set Byte,short and long example by using Prepared

Statement!");

Connection con = null;

try{

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

con = DriverManager.getConnection("jdbc:mysql:

//localhost:3306/jdbctutorial","root","root");

try{

String sql = "INSERT datatypes VALUES(?,?,?)";

PreparedStatement prest = con.prepareStatement(sql);

prest.setByte(1,(byte)5);

prest.setShort(2,(short)65);

prest.setLong(3,(long)254);

int row = prest.executeUpdate();

System.out.println(row + " row(s) affected)");

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}}}

Database Table: datatypes

d_type d_smt d_

7 65 352

8 6565 1556

10 6565 1556

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac SetByteSortLong.java

C:\vinod\jdbc\jdbc\PreparedStatement>java SetByteSortLong

Set Byte,short and long example by using Prepared Statement!

1 row(s) affected)

Page 92: JDBC Example With MySQL

92

After executing the program:

Database Table: datatypes

d_type d_smt d_

7 65 352

8 6565 1556

10 6565 1556

35 6565 155645

Page 93: JDBC Example With MySQL

93

In this JDBC section we are going to learn about the big decimal and how can be set it in the

database table by using the PreparedStatement interface of java.sql package. But here arises a

question, what is big decimal and which type to use this in the database. We know that using

of both data types MySQL and Java programming language are not same. So mapping

between both is essential to integrate to each other, here we will work on the big decimal data

type in java to integrate in MySQL through the help of NUMERIC and DECIMAL data types.

See detail description below:

Description of program:

In this program we are going to insert big decimal data type in the database table (bigdecimal)

through the use of PreparedStatement interface. Here, first of all we need to establish the

connection with MySQL database by using the JDBC driver. After establishing the connection

we will give own query in the prepareStatement method that provides us the

PreparedStatement object. Now we will add all data in the data according to database table

(Records, sal) . The sal column contains the big decimal data types. When we will get added

data in the database table then it will provide a message "Successfully!" otherwise it shows

"SQL statement is not executed!".

Description of code:

BigDecimal(String val);

This is the constructor of java.sql.BigDecimal class that takes one string type argument and

translates it into a BigDecimal.

setBigDecimal( int index, BigDecimal big);

Above method takes integer type index number another is BigDecimal types number and sets

an arguments to the given java.math.BigDecimal value.

Here is the code of program:

import java.sql.*;

import java.math.*;

public class SetBigDecimal{

public static void main(String[] args) {

BigDecimal str = null;

System.out.println("Set BigDecimal Example!");

Page 94: JDBC Example With MySQL

94

Connection con = null;

try{

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

con = DriverManager.getConnection("jdbc:mysql:

//localhost:3306/jdbctutorial","root","root");

try{

String sql = "INSERT bigdecimal VALUES(?,?)";

PreparedStatement prest = con.prepareStatement(sql);

prest.setString(1,"Deepak");

str = new BigDecimal("54547751418641878415841554878454");

prest.setBigDecimal(2,str);

prest.executeUpdate();

System.out.println("Successfully!");

}

catch (SQLException s){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac SetBigDecimal.java

C:\vinod\jdbc\jdbc\PreparedStatement>java SetBigDecimal

Set BigDecimal Example!

Successfully!

Page 95: JDBC Example With MySQL

95

Database Table: bigdecimal

Records sal

Rajesh 5.45152565625456e+032

Santhosh 5.45155487845426e+040

Tapan 5451554878454

Deepak 5.45477514186419e+031

Page 96: JDBC Example With MySQL

96

This JDBC tutorial helps us for setting date in the database table by using the

PreparedStatement interface of java.sql package. Sometimes, if you want to insert the data into

database table with date this will provide a setDate method to set the date in table. Here, we are

going to provide an example with code for adding the date in table. See brief description

below:

Description of program:

In this program we are going to insert the date in database table (Records) with the help of

PreparedStatement interface. For this, we establish the connection firstly. After establishing

the connection you need to insert an appropriate data according to Records table (Stu_roll,

Stu_name and Admin_date) in prepareStatement method that returns the PreparedStatement

object. Here we add date by using the setDate method. Finally we will get all data that are

inserted into the database table (Records) and it will display a message "row(s) affected"

otherwise it shows "SQL statement is not executed!".

Description of code:

setDate(int index, Date d):

This method sets an arguments to java.sql.Date value. The JDBC driver converts java.sql.Date

into SQL DATE value in the database.

Here is the code of progam:

import java.sql.*;

public class SetDate{

public static void main(String[] args) {

System.out.println("Prepared statement set date example!");

Connection con = null;

Date date = new Date(0000-00-00);

try{

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

con = DriverManager.getConnection("jdbc:mysql:

//localhost:3306/jdbctutorial","root","root");

try{

PreparedStatement prest = con.prepareStatement("INSERT Records

VALUES(?,?,?)");

prest.setInt(1,001);

prest.setString(2,"Raj kumar");

prest.setDate(3,date.valueOf("1998-1-17"));

int row = prest.executeUpdate();

System.out.println(row + " row(s) affected");

Page 97: JDBC Example With MySQL

97

}

catch (SQLException s){

System.out.println("SQL stattement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}}}

Database Table: Records

Stu_roll Stu_name Admin_date

1 Raj kumar 1998-01-17

2 Santosh

kashyap 1984-12-20

2 Rahul raj 1974-08-27

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac SetDate.java

C:\vinod\jdbc\jdbc\PreparedStatement>java SetDate

Prepared statement set date example!

1 row(s) affected

After executing the program:

Database Table: Records

Stu_roll Stu_name Admin_date

1 Raj kumar 1998-01-17

2 Santosh kashyap 1984-12-20

2 Rahul raj 1974-08-27

3 vinod kumar 1984-01-12

Page 98: JDBC Example With MySQL

98

In this section you will learn about setting the time in database table by using the

PreparedStatement interface of java.sql package. Suppose you want to insert the actual time in

a table, here you will provide a setTime method for setting the time. See below for an example

with code that insert the time in JDBC table.

Description of program:

This example helps us for setting the time in database table (child) by using the

PreparedStatement interface. First of all we need to establish the connection with MySQL

database through the help of JDBC deriver. After establishing the connection, we will insert

our query in the prepareStatement method that returns the PreparedStatement object. With the

help of this object we insert all data with time. Here, we will only insert the child name and

born time by using the setString and setTime methods. Finally you will get all data that are

added in the database table (child) and it will show "row(s) affected" otherwise it will display a

message "SQL statement is not executed!".

Description of code:

setTime(int index, Time t);

Above method takes integer type value and time type value. This method sets the arguments to

java.sql.Time value that is converted into SQL TIME value.

Here is the code program:

import java.sql.*;

public class SetTime{

public static void main(String[] args) {

System.out.println("Prepared Statement Set Time example!");

Connection con = null;

Time time = new Time(00-00-00);

try{

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

con = DriverManager.getConnection("jdbc:mysql:

//localhost:3306/jdbctutorial","root","root");

try{

String sql = "INSERT child VALUES(?,?)";

PreparedStatement prest = con.prepareStatement(sql);

Page 99: JDBC Example With MySQL

99

prest.setString(1,"vinod");

prest.setTime(2,time.valueOf("1:60:60"));

int row = prest.executeUpdate();

System.out.println(row + " row(s) affectec)");

}

catch (SQLException e){

System.out.println("SQL statement is not executed!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: child

ch_name b_time

Santosh 12:08:36

vinod 02:01:00

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac SetTime.java

C:\vinod\jdbc\jdbc\PreparedStatement>java SetTime

Prepared Statement Set Time example!

1 row(s) affectec)

Page 100: JDBC Example With MySQL

100

After executing the program:

Database Table: child

ch_name b_time

Santosh 12:08:36

vinod 02:01:00

Deepak 09:45:57

Page 101: JDBC Example With MySQL

101

In this JDBC tutorial we will teach how to set the Timestamp in database table by using the

PreparedStatement interface of java.sql package. If you want to insert the Timestamp in a

table, here you will provide the setTimestamp method that added date and time in the database

table by using the java.util.Date package. See brief description below:

Description of program:

In this program we are going to insert the Timestamp in database table (ray) with the help of

PreparedStatement interface. Working with program, first of we will establish the connection

with MySQL database by using the JDBC driver. When the connection has been established

then we give own query in the prepareStatement method that returns the PreparedStatement

object. After that, we will insert the data with the PreparedStatement object according to

database table (rname, rtime). Here we wish to add Timestamp in the table through the

setTimestamp method that added the timestamp in a database table. Finally, we will get the

data added in the database table then it will display a message "row(s) affected" otherwise it

shows "Illegal argument!".

Description of code:

Timestamp(long time);

This is the constructor of java.sql.Timestamp class that takes long types values to milliseconds.

The Timestamp object stored the fractional seconds but the integral seconds are stored in the

underlying date value.

setTimestamp(int index, Timestamp time);

Above method sets the arguments to given java.sql.Timestamp value. The JDBC driver

converts it into the SQL TIMESTAMP value. It takes integer type index value and Timestamp

value in millisecond.

Here is the code of program:

import java.sql.*;

public class SetTimetamp{

public static void main(String[] args) {

System.out.println("Set Timestamp example by using the Prepared

Statement!");

Connection con = null;

Timestamp tstamp = new Timestamp(00-00-00);

try{

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

con = DriverManager.getConnection("jdbc:mysql:

Page 102: JDBC Example With MySQL

102

//localhost:3306/jdbctutorial","root","root");

try{

String sql = "INSERT ray VALUES(?,?)";

PreparedStatement prest = con.prepareStatement(sql);

prest.setString(1,"x-ray");

prest.setTimestamp(2,tstamp.valueOf("1980-01-14 12:50:45.01"));

int row = prest.executeUpdate();

System.out.println(row + " row(s) affected)");

}

catch (IllegalArgumentException s){

System.out.println("Illegal argument!");

}

}

catch (Exception e){

e.printStackTrace();

}

}

}

Database Table: ray

rname rtime

x-ray 1984-11-25 02:25:45

x-ray 1980-01-14 12:50:45

Output of program:

C:\vinod\jdbc\jdbc\PreparedStatement>javac SetTimetamp.java

C:\vinod\jdbc\jdbc\PreparedStatement>java SetTimetamp

Set Timestamp example by using the Prepared Statement!

1 row(s) affected)

Page 103: JDBC Example With MySQL

103

Database Table: ray

rname rtime

x-ray 1984-11-25 02:25:45

x-ray 1980-01-14 12:50:45

Bita-ray 1984-11-23 13:01:00

Page 104: JDBC Example With MySQL

104

In this section, you will learn how to read the records of a simple text file and write (insert)

into a simple table in MySQL database. All records are written in the simple text file and

again, if you need to insert these records in tabular format the following example will provide

the facility for writing this content.

Description of program:

The following program helps you in writing the records in the MySQL database table from

the simple text file. For this, you must have to create a simple text file that have to be inserted

the records into a database table. This program uses the simple Text file (Employee_list.txt)

that contains all employees record (id, Emp_name, Emp_depart and sal). After creating a text

file, you should establish the connection with MySQL database. Here, we applying the

connection() method that will provide the connection and another is TextFileToTable()

method that helps you for writing or inserting the records into a MySQL database table

(Employee_Records). The inserting process is completely successfully, it will show a message

"All data are inserted in the database table".

Description of code:

StringTokenizer(String data, String comma):

This is the constructor of StringTokenizer class that allows the permission for breaking an

application into tokens. It constructs a string tokenizer for the given string. The characters are

separated by the comma arguments.

nextToken():

This is the method that returns the next tokens from the StringTokenizer object.

Here is the code of program:

import java.sql.*;

import java.io.*;

import java.util.*;

public class TextFileToTable{

Connection con = null;

Statement st;

public static void main(String[] args) {

System.out.println("Write Text File to Table!");

TextFileToTable text = new TextFileToTable();

}

public Connection connection(){

try{

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

}

Page 105: JDBC Example With MySQL

105

catch(ClassNotFoundException c){

System.out.println("Class not found!");

}

try{

con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/jdbctutorial","root","root");

}

catch(SQLException s){

System.out.println("Connection is not found!");

}

return con;

}

public TextFileToTable(){

try{

FileInputStream fstream = new FileInputStream("Employee_list.txt");

DataInputStream dstream = new DataInputStream(fstream);

BufferedReader bf = new BufferedReader(new InputStreamReader(dstream));

String data = null;

String comma = ",";

while((data = bf.readLine()) != null){

StringTokenizer stoken = new StringTokenizer(data,comma);

String Emp_id = stoken.nextToken();

int id = Integer.parseInt(Emp_id);

String Emp_name = stoken.nextToken();

String Emp_depart = stoken.nextToken();

String Emp_sal = stoken.nextToken();

int sal = Integer.parseInt(Emp_sal);

st = connection().createStatement();

int row = st.executeUpdate("INSERT Employee_Records VALUES

("+id+" , '"+Emp_name+"'"+" , '"+Emp_depart+"' ,"+sal+")");

}

System.out.println("All data are inserted in the database table");

bf.close();

st.close();

}

catch(Exception e){

e.printStackTrace();

}

}

}

Page 106: JDBC Example With MySQL

106

In this section, you will learn to copy one table to another in a same MySQL database.

Description of Code:

This program helps you in copying one table to another in a same MySQL database. To copy any

table, firstly, you need to establish the connection with MySQL database (jdbc4). This database has

both the tables (Copyemployee and employee table). That is the one which is to be copied to the other

table and the second is the table to be copied. For copying a table, we have applied the ?INSERT INTO

Copyemployee SELECT * FROM employee? SQL statement. Whenever a table is copied, it displays

?Numbers of row(s) affected?. If none of the rows is copied then it shows a message ?Don?t add any

row!?.

[Note: Both tables have the same field and its data type.]

Syntax for copy tables:

INSERT INTO <new_table_name> SELECT * FROM <old_table_name>

Here is code of program:

import java.sql.*;

public class CopyOneTableToAnother{

public static void main(String[] args) {

System.out.println("Copy data from one table

to another in a database!");

Connection conn = null;

String url = "jdbc:mysql://localhost:3306/";

String dbName = "jdbc4";

String driver = "com.mysql.jdbc.Driver";

String userName = "root";

String password = "root";

try {

//Load jdbc driver

Class.forName(driver).newInstance();

//Establish the connection

Page 107: JDBC Example With MySQL

107

conn = DriverManager.getConnection(url+dbName,userName,password);

Statement st = conn.createStatement();

//Copy table

int rows = st.executeUpdate("INSERT INTO Copyemployee

SELECT * FROM employee");

if (rows == 0){

System.out.println("Don't add any row!");

}

else{

System.out.println(rows + " row(s)affected.");

conn.close();

}

}

catch (Exception e) {

e.printStackTrace();

} }}

Table Name: employee

empId empName empSal

1 Vinod 50000

2 Sushil 80000

Table Name: Copyemployee

empId empName empSal

8 AmarDeep 10000

7 Noor 50000

Page 108: JDBC Example With MySQL

108

Output of this program:

C:\vinod>javac CopyOneTableToAnother.java

C:\vinod>

C:\vinod>java CopyOneTableToAnother

Copy data from one table to another in a database!

2 row(s)affected.

C:\vinod>

After copy table: Copyemployee

empId empName empSal

8 AmarDeep 10000

7 Noor 50000

1 Vinod 50000

2 Sushil 80000

Page 109: JDBC Example With MySQL

109

In this section, you will learn to copy one database table to another database table. That

means we copy one table to a different table but it contains a similar type of field or column.

These tables aren?t in same database. Both the MySQL databases are different i.e. jdbc4 and

jdbcMysql. The "jdbc4" database has "Copyemployee" table and "jdbcMysql" database also

has a "Roseindia" table.

To copy the table you need to establish the connection with the MySQL database (jdbcMysql).

When the connection is established then sql statement (?INSERT INTO Roseindia SELECT *

FROM jdbc4.Copyemployee?) is executed and rows get copied. Once the rows get copied then

it will display a message - ?number of row(s) affected!?. Whenever any row is not copied then

it shows a message - ?Don?t add any row!?.

Syntax for copy table:

?INSERT INTO <new_table_name> SELECT * FROM <Database_name.old_table_name>

Here is the code of program:

import java.sql.*;

public class CopyOneDatabaseTableToAnother {

public static void main(String[] args) {

System.out.println("Copy data from one database table to another!");

Connection conn = null;

String url = "jdbc:mysql://localhost:3306/";

String dbName = "jdbcMysql";

String driver = "com.mysql.jdbc.Driver";

String userName = "root";

String password = "root";

try {

Class.forName(driver).newInstance();

conn = DriverManager.getConnection(url+dbName,userName,password);

Statement st = conn.createStatement();

//Copy table

int rows = st.executeUpdate("INSERT INTO Roseinda SELECT * FROM jdbc4.Copyemployee");

if (rows == 0){

System.out.println("Don't add any row!");

Page 110: JDBC Example With MySQL

110

}

else{

System.out.println(rows + " row(s)affected.");

conn.close();

}

}

catch (Exception e) {

e.printStackTrace();

}

}

}

Table Name: Copyemployee(jdbc4)

empId empName empSal

8 AmarDeep 10000

7 Noor 50000

1 Vinod 50000

2 Sushil 80000

Table Name: Roseindia(jdbcMysql)

empId empName empSal

10 Suman

saurabh 19000

11 Ravi 25000

Page 111: JDBC Example With MySQL

111

Output of this program:

C:\vinod>javac CopyOneDatabaseTableToAnother.java

C:\vinod>java CopyOneDatabaseTableToAnother

Copy data from one database table to another!

4 row(s)affected.

C:\vinod>

After copy table: Roseindia(jdbcMysql)

empId empName empSal

10 Suman saurabh 19000

11 Ravi 25000

8 AmarDeep 10000

7 Noor 50000

1 Vinod 50000

2 Sushil 80000

Page 112: JDBC Example With MySQL

112

In this example we are inserting data into a table using stored procedure.

Steps:

1.Create database:

To create database we use syntax: create database database_name. We can create database

with the name "Employee" as

mysql> create database

Employee;

Query OK, 1 row affected

(0.09 sec)

2.Change the database:

We are using use database_name; to change the database

mysql> use employee;

Database changed

3.Create the table:

mysql> create table emp(name char(12),fathername

char(12),password char(12));

Query OK, 0 rows affected (0.55 sec)

4.Create procedure :

1.We can use delimiter to create multiple statements. To create delimiter we can use following

syntax.

mysql> DELIMITER //

2.To create procedure we use following syntax:

mysql>create procedure procedure_name(IN |OUT | INOUT) param_name type)

3.We write sql statement into begin......end body. To start begin use mysql>begin and to end

Page 113: JDBC Example With MySQL

113

use: mysql>end;

4.To finish the procedure use mysql>// delimiter.

mysql> delimiter //

mysql> create procedure empproc(in name char(12),in

fathername char(12),in password char(12))

-> begin

-> insert into emp values(name,fathername,password);

-> end;

-> //

Query OK, 0 rows affected (0.22 sec)

5.Step to load driver:

To load the driver we are using syntax:

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

6.Steps to make connection:

We are using getConnection("url/database","user","password") method to create a

connection.

Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","ro

ot","root");

7.Step to call procedure:

We are using CallableStatement to execute a stored procedure into java code. The following

syntax is used to create an object of CallableStatement interface.

CallableStatement calstat=conn.prepareCall("{call empproc(?,?,?)}");

8.Step to pass the values into procedure:

To set the values we are using setXXX(). Here XXX is data type Object class name, e.g

setString() to pass string in procedure.

9.Step to execute query :

To execute query we can use:

ResultSet rs = calstat.executeQuery();

10.Close connection :

calstat.close();

Page 114: JDBC Example With MySQL

114

The code of the program is given below:

import java.sql.*;

public class Insert_EMP{

public static void main(String a[])throws Exception {

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

Connection conn=DriverManager.getConnection("jdbc:mysql:

//localhost:3306/employee","root","root");

CallableStatement calstat=conn.prepareCall("{call

empproc(?,?,?)}");

calstat.setString(1,a[0]);

calstat.setString(2,a[1]);

calstat.setString(3,a[2]);

ResultSet rs = calstat.executeQuery();

conn.close();

calstat.close();

System.out.println("Your data has been inserted into table.");

}

}

The code of the stored procedure is given below:

delimiter //

create procedure empproc(in name char(12),in fathername

char(12),in password char(12))

begin

insert into emp values(name,fathername,password);

end;

//

The output of the program is given below:

C:\rajesh\mysql>javac Insert_EMP.java

C:\rajesh\mysql>java Insert_EMP Rajesh Ram Raju

Your data has been inserted into table.

Page 115: JDBC Example With MySQL

115

In this section, you will learn to insert an image to the MySQL database table.

Flow of the process :

This program helps the user to insert an image in the MySQL database table. To insert an image, you

need to establish a connection with MySQL database. Lets' take a database hibernatetutorial, in our

case. This database has a table (Image table). For inserting an image in table, we have used the SQL

statement ?INSERT INTO Image values(?,?,?)? with the prepareStatement() method. Whenever an

image is inserted into the database, it displays ?Inserting Successfully?. If it fails to insert an image

then it throws an exception.

[Note: The table has a specified field (or data type) to store an image of type e.g. Blob]

Here is the Code of Program :

import java.sql.*;

import java.io.*;

public class insertImage{

public static void main(String[] args) {

System.out.println("Insert Image Example!");

String driverName = "com.mysql.jdbc.Driver";

String url = "jdbc:mysql://localhost:3306/";

String dbName = "hibernatetutorial";

String userName = "root";

String password = "root";

Connection con = null;

try{

Class.forName(driverName);

con = DriverManager.getConnection(url+dbName,userName,password);

Statement st = con.createStatement();

File imgfile = new File("images.jpg");

FileInputStream fin = new FileInputStream(imgfile);

PreparedStatement pre = con.prepareStatement("insert into Image

values(?,?,?)");

pre.setInt(1,5);

pre.setString(2,"Durga");

pre.setBinaryStream(3,fin,(int)imgfile.length());

pre.executeUpdate();

System.out.println("Inserting Successfully!");

pre.close();

con.close(); }

catch (Exception e){

System.out.println(e.getMessage());

}}}

Page 116: JDBC Example With MySQL

116

Output of this Program:

C:\Roseindia\vinod\jdbc4.0>javac insertImage.java

C:\Roseindia\vinod\jdbc4.0>java insertImage

Insert Image Example!

Inserting Successfully!

C:\Roseindia\vinod\jdbc4.0>

Table Name: Image

Durga.jpg

Page 117: JDBC Example With MySQL

117

In this Tutorial we want to explain you a code that makes you to understand JDBC

MysqlConnection String. The code include a class JdbcMysqlConnectionString,Inside this

class we have a main method that follow the list of steps -

1)The first step is to import a package java.sql.* - This provides you a network interface that

communicate between front end application in java and database.

2)Loading a driver is the next step by calling a class class.forname( ) and accept driver class as

argument.

3)DriverManager.getConnection( ) - This is used to built a connection between url and

database.

Finally the print ln print the connection value, username and password. In case there is an

exception in try block, the subsequent catch block caught and handle the exception occurred

in try block.

4)e,printStacktrace( ) - This method print the list of all methods that are currently executed at

that time. It also contain message string information about the error.

JdbcMysqlConnectionString.java.java

import java.sql.*;

public class JdbcMysqlConnectionString {

static public final String driver = "com.mysql.jdbc.Driver";

static public final String connection =

"jdbc:mysql://localhost:3306/komal";

static public final String user = "root";

static public final String password = "root";

public static void main(String args[]) {

try {

Class.forName(driver);

Connection con =

DriverManager.getConnection(connection, user, password);

System.out.println("Jdbc Mysql Connection String :");

System.out.println(connection);

System.out.println("User Name :" + user);

System.out.println("Password :" + password);

if (!con.isClosed()) {

con.close();

}

Page 118: JDBC Example With MySQL

118

} catch (Exception e) {

e.printStackTrace();

}

}

}

Output

Jdbc Mysql Connection String :

jdbc:mysql://localhost:3306/komal

User Name :root

Password :root


Recommended