0% found this document useful (0 votes)
23 views24 pages

JDBC Chapter Java

The document provides an overview of Java's File class for file and directory operations, including methods for creating directories and files. It also covers reading and writing files using FileWriter and FileReader, along with Java's Date class for handling date and time. Additionally, it discusses regular expressions, serialization and deserialization, and JDBC for database connectivity, detailing driver types and architecture.

Uploaded by

jaindeshna468
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views24 pages

JDBC Chapter Java

The document provides an overview of Java's File class for file and directory operations, including methods for creating directories and files. It also covers reading and writing files using FileWriter and FileReader, along with Java's Date class for handling date and time. Additionally, it discusses regular expressions, serialization and deserialization, and JDBC for database connectivity, detailing driver types and architecture.

Uploaded by

jaindeshna468
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

The class named File of the java.io package represents a file or directory (path names) in the system.

This class provides various methods to perform various operations on files/directories.

Creating a new directory

The mkdir() method of this class creates a directory with the path represented by the current object.

Therefore, to create a directory −

Instantiate the File class by passing the path of the directory you need to create, as a parameter (String).

Invoke the mkdir() method using the above created file object.

Example

Following Java example reads the path and name of the directory to be created, from the user, and
creates it.

import java.io.File;

import java.util.Scanner;

public class CreateDirectory {

public static void main(String args[]) {

System.out.println("Enter the path to create a directory: ");

Scanner sc = new Scanner(System.in);

String path = sc.next();

System.out.println("Enter the name of the desired a directory: ");

path = path+sc.next();

//Creating a File object

File file = new File(path);

//Creating the directory

boolean bool = file.mkdir();

if(bool){

System.out.println("Directory created successfully");


}else{

System.out.println("Sorry couldn’t create specified directory");

}}}

How to Create a File in Java

In Java, creating a file is easy by using pre-defined classes and packages. There are three ways to create
a file.

Using File.createNewFile() method

Using FileOutputStream class

Using File.createFile() method

Java File.createNewFile() method

The File.createNewFile() is a method of File class which belongs to a java.io package. It does not accept
any argument. The method automatically creates a new, empty file. The method returns a boolean
value:

true, if the file created successfully.

false, if the file already exists.

When we initialize File class object, we provide the file name and then we can call createNewFile()
method of the File class to create a new file in Java.

The File.createNewFile() method throws java.io.IOException if an I/O error occurred. It also throws
SecurityException if a security manager exists and its SecurityManager.checkWriter(java.lang.String)
method denies write access to the file. The signature of the method is:

public boolean createNewFile() throws IOException

We can pass the file name or absolute path or relative path as an argument in the File class object. For a
non-absolute path, File object tries to locate the file in the current directory.
READING AND WRITING TO FILE

Java FileWriter and FileReader classes are used to write and read data from text files (they are Character
Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you
have to read and write any textual information as these are Byte stream classes.

FileWriter

FileWriter is useful to create a file writing characters into it.

This class inherits from the OutputStream class.

The constructors of this class assume that the default character encoding and the default byte-buffer
size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a
FileOutputStream.

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a
FileOutputStream.

FileWriter creates the output file if it is not present already.

Constructors:

FileWriter(File file) – Constructs a FileWriter object given a File object.

FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.

FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.

FileWriter (String fileName) – constructs a FileWriter object given a file name.

FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a
Boolean indicating whether or not to append the data written.

Methods:

public void write (int c) throws IOException – Writes a single character.

public void write (char [] stir) throws IOException – Writes an array of characters.

public void write(String str)throws IOException – Writes a string.

public void write(String str, int off, int len)throws IOException – Writes a portion of a string. Here off is
offset from which to start writing characters and len is the number of characters to write.

public void flush() throws IOException flushes the stream


public void close() throws IOException flushes the stream first and then closes the writer.

FileReader

FileReader is useful to read data in the form of characters from a ‘text’ file.

This class inherited from the InputStreamReader Class.

The constructors of this class assume that the default character encoding and the default byte-buffer
size are appropriate. To specify these values yourself, construct an InputStreamReader on a
FileInputStream.

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using
a FileInputStream.

Constructors:

FileReader(File file) – Creates a FileReader , given the File to read from

FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from

FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from

Methods:

public int read () throws IOException – Reads a single character. This method will block until a character
is available, an I/O error occurs, or the end of the stream is reached.

public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block
until some input is available, an I/O error occurs, or the end of the stream is reached.

public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion
of an array. This method will block until some input is available, an I/O error occurs, or the end of the
stream is reached.

Parameters:

cbuf – Destination buffer

off – Offset at which to start storing characters

len – Maximum number of characters to read


public void close() throws IOException closes the reader.

public long skip(long n) throws IOException –Skips characters. This method will block until some
characters are available, an I/O error occurs, or the end of the stream is reached.

Parameters:

n – The number of characters to skip

DATE AND TIME

Java provides the Date class available in java.util package, this class encapsulates the
current date and time.
The Date class supports two constructors as shown in the following table.

Sr.No Constructor & Description


.

1
Date( )
This constructor initializes the object with the current date and time.

2
Date(long millisec)
This constructor accepts an argument that equals the number of milliseconds
that have elapsed since midnight, January 1, 1970.

Following are the methods of the date class.

Sr.No Method & Description


.

1
boolean after(Date date)
Returns true if the invoking Date object contains a date that is later than the
one specified by date, otherwise, it returns false.

2
boolean before(Date date)
Returns true if the invoking Date object contains a date that is earlier than the
one specified by date, otherwise, it returns false.

3
Object clone( )
Duplicates the invoking Date object.

4
int compareTo(Date date)
Compares the value of the invoking object with that of date. Returns 0 if the
values are equal. Returns a negative value if the invoking object is earlier than
date. Returns a positive value if the invoking object is later than date.

5
int compareTo(Object obj)
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it
throws a ClassCastException.

6
boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date as the
one specified by date, otherwise, it returns false.

7
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.

8
int hashCode( )
Returns a hash code for the invoking object.

9
void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time
in milliseconds from midnight, January 1, 1970.

10
String toString( )
Converts the invoking Date object into a string and returns the result.
Sr.No Method & Description
.

1
void add(int field, int amount)
Adds the specified (signed) amount of time to the given time field, based on the
calendar's rules.

2
protected void computeFields()
Converts UTC as milliseconds to time field values.

3
protected void computeTime()
Overrides Calendar Converts time field values to UTC as milliseconds.

4
boolean equals(Object obj)
Compares this GregorianCalendar to an object reference.

5
int get(int field)
Gets the value for a given time field.

6
int getActualMaximum(int field)
Returns the maximum value that this field could have, given the current date.

7
int getActualMinimum(int field)
Returns the minimum value that this field could have, given the current date.

8
int getGreatestMinimum(int field)
Returns highest minimum value for the given field if varies.

9
Date getGregorianChange()
Gets the Gregorian Calendar change date.
10
int getLeastMaximum(int field)
Returns lowest maximum value for the given field if varies.

11
int getMaximum(int field)
Returns maximum value for the given field.

12
Date getTime()
Gets this Calendar's current time.

13
long getTimeInMillis()
Gets this Calendar's current time as a long.

14
TimeZone getTimeZone()
Gets the time zone.

15
int getMinimum(int field)
Returns minimum value for the given field.

16
int hashCode()
Overrides hashCode.

REGULAR EXPRESSION

What is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern. When you search for data
in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to
work with regular expressions. The package includes the following classes:
Pattern Class - Defines a pattern (to be used in a search)

Matcher Class - Used to search for the pattern

PatternSyntaxException Class - Indicates syntax error in a regular expression pattern

Find out if there are any occurrences of the word "w3schools" in a sentence:

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String[] args) {

Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);

Matcher matcher = pattern.matcher("Visit W3Schools!");

boolean matchFound = matcher.find();

if(matchFound) {

System.out.println("Match found");

} else {

System.out.println("Match not found");

SERIALIZATION AND DESERIALIZATION

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used
in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted into an
object. The serialization and deserialization process is platform-independent, it means you can serialize
an object on one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for
deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization

It is mainly used to travel object's state on the network (that is known as marshalling).

java.io.Serializable interface

Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so
that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker
interfaces.

The Serializable interface must be implemented by the class whose object needs to be persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface by default.

Deserialization

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized
object.
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized
object.

What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database. Java can be used to write
different types of executables, such as −
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −
 JDBC API − This provides the application-to-JDBC Manager connection.
 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application −

What is JDBC Driver?


JDBC drivers implement the defined interfaces in the JDBC API, for interacting with
your database server.
For example, using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their
behaviours defined and their actual implementaions are done in third-party drivers.
Third party vendors implements the java.sql.Driver interface in their database driver.

JDBC Drivers Types


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types
into four categories, Types 1, 2, 3, and 4, which is explained below −

Type 1 − JDBC-ODBC Bridge Driver


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each
client machine. Using ODBC, requires configuring on your system a Data Source Name
(DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only
supported ODBC access but now this type of driver is recommended only for
experimental use or when no other alternative is available.

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of
driver.

Type 2 − JDBC-Native API


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors
and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver
must be installed on each client machine.
If we change the Database, we have to change the native API, as it is specific to a
database and they are mostly obsolete now, but you may realize some speed increase
with a Type 2 driver, because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3 − JDBC-Net pure Java


In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients
use standard network sockets to communicate with a middleware application server.
The socket information is then translated by the middleware application server into the
call format required by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client
and a single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.

Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and
properties that enable you to send SQL or PL/SQL commands and receive data from
your database.
They also define methods that help bridge data type differences between Java and SQL
data types used in a database.
The following table provides a summary of each interface's purpose to decide on the
interface to use.

Interfaces Recommended Use

Statement Use this for general-purpose access to your database. Useful when
you are using static SQL statements at runtime. The Statement
interface cannot accept parameters.

PreparedStatement Use this when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.

CallableStatement Use this when you want to access the database stored procedures.
The CallableStatement interface can also accept runtime input
parameters.

The Statement Objects


Creating Statement Object
Before you can use a Statement object to execute a SQL statement, you need to create
one using the Connection object's createStatement( ) method, as in the following
example −
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
...
}
Once you've created a Statement object, you can then use it to execute an SQL
statement with one of its three execute methods.
 boolean execute (String SQL): Returns a boolean value of true if a ResultSet
object can be retrieved; otherwise, it returns false. Use this method to execute
SQL DDL statements or when you need to use truly dynamic SQL.
 int executeUpdate (String SQL) − Returns the number of rows affected by the
execution of the SQL statement. Use this method to execute SQL statements for
which you expect to get a number of rows affected - for example, an INSERT,
UPDATE, or DELETE statement.
 ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this
method when you expect to get a result set, as you would with a SELECT
statement.

Closing Statement Object


Just as you close a Connection object to save database resources, for the same reason
you should also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object
first, it will close the Statement object as well. However, you should always explicitly
close the Statement object to ensure proper cleanup.
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
stmt.close();
}
For a better understanding, we suggest you to study the Statement - Example tutorial.

The PreparedStatement Objects


The PreparedStatement interface extends the Statement interface, which gives you
added functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
Creating PreparedStatement Object
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
All parameters in JDBC are represented by the ? symbol, which is known as the
parameter marker. You must supply values for every parameter before executing the
SQL statement.
The setXXX() methods bind values to the parameters, where XXX represents the Java
data type of the value you wish to bind to the input parameter. If you forget to supply the
values, you will receive an SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array
indices, which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(),
(b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement
object. However, the methods are modified to use SQL statements that can input the
parameters.

Closing PreparedStatement Object


Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object
first, it will close the PreparedStatement object as well. However, you should always
explicitly close the PreparedStatement object to ensure proper cleanup.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}

RESULTSET
The SQL statements that read data from a database query, return the data in a result
set. The SELECT statement is the standard way to select rows from a database and
view them in a result set. The java.sql.ResultSet interface represents the result set of a
database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The
term "result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
 Navigational methods − Used to move the cursor around.
 Get methods − Used to view the data in the columns of the current row being
pointed by the cursor.
 Update methods − Used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are
designated when the corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired
ResultSet −
 createStatement(int RSType, int RSConcurrency);
 prepareStatement(String SQL, int RSType, int RSConcurrency);
 prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second argument is
one of two ResultSet constants for specifying whether a result set is read-only or
updatable.

Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result


set.
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward,
and the result set is not sensitive to changes
made by others to the database that occur after
the result set was created.

ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward,


and the result set is sensitive to changes made
by others to the database that occur after the
result set was created.

CREATE,UPDATE AND DELETE OPERATIONS.


This JDBC tutorial is going to help you learning how to do basic database operations (CRUD - Create,
Retrieve, Update and Delete) using JDBC (Java Database Connectivity) API. These CRUD operations are
equivalent to the INSERT, SELECT, UPDATE and DELETE statements in SQL language. Although the target
database system is MySQL, but the same technique can be applied for other database systems as well
because the query syntax used is standard SQL which is supported by all relational database systems.

We will learn how to do insert, query, update and delete database records by writing code to manage
records of a table Users in a MySQL database called SampleDB.

Table of content:

1.
1. Prerequisites
2. Creating a sample MySQL database
3. Understand the principal JDBC interfaces and classes
4. Connecting to the database
5. Executing INSERT statement
6. Executing SELECT statement
7. Executing UPDATE statement
8. Executing DELETE statement

1. Prerequisites
To begin, make sure you have the following pieces of software installed on your computer:

o JDK (download JDK 7).
o MySQL (download MySQL Community Server 5.6.12). You may also want to download
MySQL Workbench - a graphical tool for working with MySQL databases.
o JDBC Driver for MySQL (download MySQL Connector/J 5.1.25). Extract the zip archive and
put the mysql-connector-java-VERSION-bin.jar file into classpath (in a same folder as
your Java source files).

2. Creating a sample MySQL database


Let’s create a MySQL database called SampleDB with one table Users with the following structure:

Execute the following SQL script inside MySQL Workbench:


1
2 create database SampleDB;
3
use SampleDB;
4
5 CREATE TABLE `users` (
6 `user_id` int(11) NOT NULL AUTO_INCREMENT,
7 `username` varchar(45) NOT NULL,
8 `password` varchar(45) NOT NULL,
`fullname` varchar(45) NOT NULL,
9
`email` varchar(45) NOT NULL,
10 PRIMARY KEY (`user_id`)
11 );
12
Or if you are using MySQL Command Line Client program, save the above script into a file, let’s
say, SQLScript.sqland execute the following command:
source Path\To\The\Script\File\SQLScript.sql
Here’s an example screenshot taken while executing the above script in MySQL Command Line
Client program:

3. Understand the main JDBC interfaces and classes


Let’s take an overview look at the JDBC’s main interfaces and classes with which we usually work.
They are all available under the java.sql package:


o DriverManager: this class is used to register driver for a specific database type (e.g.
MySQL in this tutorial) and to establish a database connection with the server via
its getConnection() method.
o Connection: this interface represents an established database connection (session) from
which we can create statements to execute queries and retrieve results, get metadata about
the database, close connection, etc.
o Statement and PreparedStatement: these interfaces are used to execute static SQL
query and parameterized SQL query, respectively. Statement is the super interface of
the PreparedStatement interface. Their commonly used methods are:

I.
o
 boolean execute(String sql): executes a general SQL statement. It
returns true if the query returns a ResultSet, false if the query returns an update
count or returns nothing. This method can be used with a Statement only.
 int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE
statement and returns an update account indicating number of rows affected (e.g. 1 row
inserted, or 2 rows updated, or 0 rows affected).
 ResultSet executeQuery(String sql): executes a SELECT statement and returns
a ResultSet object which contains results returned by the query.

A prepared statement is one that contains placeholders (in form question marks ?) for
dynamic values will be set at runtime. For example:
SELECT * from Users WHERE user_id=?
Here the value of user_id is parameterized by a question mark and will be set by one of
the setXXX() methods from the PreparedStatement interface, e.g. setInt(int
index, int value).


o ResultSet: contains table data returned by a SELECT query. Use this object to iterate over
rows in the result set using next() method, and get value of a column in the current row
using getXXX() methods (e.g. getString(), getInt(), getFloat() and so on). The
column value can be retrieved either by index number (1-based) or by column name.
o SQLException: this checked exception is declared to be thrown by all the above methods,
so we have to catch this exception explicitly when calling the above classes’ methods.

4. Connecting to the database


Supposing the MySQL database server is listening on the default port 3306 at localhost. The
following code snippet connects to the database name SampleDB by the user root and
password secret:

1 String dbURL = "jdbc:mysql://localhost:3306/sampledb";

2 String username = "root";

String password = "secret";


3

4
5
try {
6

7 Connection conn = DriverManager.getConnection(dbURL, username, password);


8

9 if (conn != null) {

10 System.out.println("Connected");

11 }

12 } catch (SQLException ex) {

ex.printStackTrace();
13
}
14
Once the connection was established, we have a Connection object which can be used to create
statements in order to execute SQL queries. In the above code, we have to close the connection
explicitly after finish working with the database:

1 conn.close();

However, since Java 7, we can take advantage of the try-with-resources statement which will close
the connection automatically, as shown in the following code snippet:

1 try (Connection conn = DriverManager.getConnection(dbURL, username, password)) {


2

3 // code to execute SQL queries goes here...

5 } catch (SQLException ex) {

6 ex.printStackTrace();

}
7

5. JDBC Execute INSERT Statement Example


Let’s write code to insert a new record into the table Users with following details:


o username: bill
o password: secretpass
o fullname: Bill Gates
o email: [email protected]

Here’s the code snippet:


1 String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?,
2

4 PreparedStatement statement = conn.prepareStatement(sql);

statement.setString(1, "bill");
5
statement.setString(2, "secretpass");
6
statement.setString(3, "Bill Gates");
7
statement.setString(4, "[email protected]");
8

9
int rowsInserted = statement.executeUpdate();
10 if (rowsInserted > 0) {
11 System.out.println("A new user was inserted successfully!");
12 }

In this code, we create a parameterized SQL INSERT statement and create


a PreparedStatement from the Connection object. To set values for the parameters in the
INSERT statement, we use the PreparedStatement‘s setString() methods because all these
columns in the table Users are of type VARCHAR which is translated to String type in Java. Note
that the parameter index is 1-based (unlike 0-based index in Java array).

The PreparedStatement interface provides various setXXX() methods corresponding to each


data type, for example:


o setBoolean(int parameterIndex, boolean x)
o setDate(int parameterIndex, Date x)
o setFloat(int parameterIndex, float x)
o …

And so on. Which method to be used is depending on the type of the corresponding column in the
database table.
Finally we call the PreparedStatement’s executeUpdate() method to execute the INSERT
statement. This method returns an update count indicating how many rows in the table were affected
by the query, so checking this return value is necessary to ensure the query was executed
successfully. In this case, executeUpdate() method should return 1 to indicate one record was
inserted.

6. JDBC Execute SELECT Statement Example


The following code snippet queries all records from the Users table and print out details for each
record:

1 String sql = "SELECT * FROM Users";


2

3
Statement statement = conn.createStatement();
4
ResultSet result = statement.executeQuery(sql);
5

6 int count = 0;
7

8 while (result.next()){
9 String name = result.getString(2);

10 String pass = result.getString(3);

11 String fullname = result.getString("fullname");

String email = result.getString("email");


12

13
String output = "User #%d: %s - %s - %s - %s";
14
System.out.println(String.format(output, ++count, name, pass, fullname, email));
15
}
16
Output:
User #1: bill - secretpass - Bill Gates - [email protected]

Because the SQL SELECT query here is static so we just create a Statement object from the
connection. The while loop iterates over the rows contained in the result set by repeatedly checking
return value of the ResultSet’s next() method. The next() method moves a cursor forward in the
result set to check if there is any remaining record. For each iteration, the result set contains data for
the current row, and we use the ResultSet’s getXXX(column index/column name) method to
retrieve value of a specific column in the current row, for example this statement:

1 String name = result.getString(2);

Retrieves value of the second column in the current row, which is the username field. The value is
casted to a String because we know that the username field is of type VARCHAR based on the
database schema mentioned previously. Keep in mind that the column index here is 1-based, the
first column will be at index 1, the second at index 2, and so on. If you are not sure or don’t know
exactly the index of column, so passing a column name would be useful:

1 String fullname = result.getString("fullname");

You might also like