JDBC Chapter Java
JDBC Chapter Java
The mkdir() method of this class creates a directory with the path represented by the current object.
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;
path = path+sc.next();
if(bool){
}}}
In Java, creating a file is easy by using pre-defined classes and packages. There are three ways to create
a file.
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:
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:
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
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.
Constructors:
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, 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 (char [] stir) throws IOException – Writes an array of characters.
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.
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
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(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:
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:
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.
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.
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
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.
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)
Find out if there are any occurrences of the word "w3schools" in a sentence:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
if(matchFound) {
System.out.println("Match found");
} else {
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.
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 −
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of
driver.
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.
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.
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
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).
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
5
try {
6
9 if (conn != null) {
10 System.out.println("Connected");
11 }
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:
6 ex.printStackTrace();
}
7
o username: bill
o password: secretpass
o fullname: Bill Gates
o email: [email protected]
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 }
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.
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);
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:
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: