JDBC – ACID Properties

JDBC – ACID Properties of Transaction ”; Previous Next What is a Transaction? A transaction is a single logical unit of operations which accesses and updates the contents of a database. ACID properties of a Transaction Transactions also have properties that must be maintained in order to keep database consistency, known as ACID properties: A for Atomicity, C for Consistency, I for Isolation, D for Durability. Atomicity − Transactions involve a group of operations performed sequentially. Atomicity says the entire group of operations either succeed or fail. Consistency − This property involves ensuring only consistent data is added to database. If any error occurs, database is moved to the initial state. Isolation − Transactions must be isolated from each other, otherwise the data maybe corrupted. Isolation levels can be read uncommitted, read committed, repeatable read and serializable. These are described in the next section. Durability − This property ensures that completed transaction will persist the data appropriately and also in the event of a server failure/system crash. Dirty Read, Non-repeatable read, Phantom Read Before understanding isolation let us understand the following basic concepts − Dirty Read − User A inserts a row into table. User B selects the row. User A cancels the transaction. Now, B has made changes to the row, but that row is not in the database anymore. Non-repeatable read − User A reads a row. User B updates the row. User A reads the row again, and sees the updated result. Phantom read − User A reads all rows in a table that satisfies a WHERE condition in SQL. User B adds a row to the same query satisfying a WHERE condition. User A does a SELECT again and finds the added row. Isolation Levels Following are five major isolation levels present in java.sql package. Sr.No. Isolation Level Description 1 TRANSACTION_NONE Transaction is not supported. 2 TRANSACTION_READ_UNCOMMITTED Unsaved data is visible to transaction. All data inconsistencies are possible. 3 TRANSACTION_READ_COMMITTED Prevents dirty read. All changes to a transaction are visible only after the transaction is committed. 4 TRANSACTION_REPEATABLE_READ Prevents dirty read, non-repeatable read. A second transaction cannot read, update or delete the rows selected by the first transaction. Does not prevent phantom reads. 5 TRANSACTION_SERIALIZABLE Strictest isolation level. Prevents dirty read, non-repeatable read, phantom read. The above isolation levels can be set in the Connection object in the java.sql package, by the setIsolationLevel method. For example, Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost/TUTORIALSPOINT”, “user”, “password”); conn.setIsolationLevel(Connection.TRANSACTION_READ_COMMITTED); Setting Isolation Level in MySQL Isolation level can also be set in the database. For MySQL − mysql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; Other permitted values are following READ COMMITTED READ UNCOMMITTED Default isolation level is REPEATABLE READ. Print Page Previous Next Advertisements ”;

JDBC – Drop Tables

JDBC – Drop Table ”; Previous Next This chapter provides an examples on how to drop a table, drop table if exists and truncate table using JDBC application. Before executing the following example, make sure you have the following in place − To execute the following example you can replace the username and password with your actual user name and password. Your MySQL or whatever database you are using, is up and running. NOTE Reformatting JDBC Tutorial This is a serious operation and you have to make a firm decision before proceeding to delete a table, because everything you have in your table would be lost. Required Steps The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Execute a queryReformatting JDBC Tutorial Requires using an object of type Statement for building and submitting an SQL statement to drop a table in a seleted database. Clean up the environment Reformatting JDBC Tutorial try with resources automatically closes the resources. Example: Dropping a Table We”re required to have DROP privileges in order to run DROP TABLE command. In this example, we”ve three static strings containing a dababase connection url, username, password. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve prepared a Statement object using createStatement() method. As next step, We”ve prepared a SQL string to drop a table REGISTRATION by calling statement.executeUpdate() method. In case of any exception while connecting to the database, a catch block handled SQLException and printed the stack trace. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { String sql = “DROP TABLE REGISTRATION”; stmt.executeUpdate(sql); System.out.println(“Table deleted in given database…”); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac JDBCExample.java C:> When you run JDBCExample, it produces the following result − C:>java JDBCExample Table deleted in given database… C:> Example: Dropping a Table if Exists A table can be dropped using following command. If it does not exist, this command will throw error. DROP TABLE table_name If we use a check before dropping a table, it will not throw an error and drops table only if table exists. DROP TABLE IF EXISTS table_name In this example, we”ve three static strings containing a dababase connection url, username, password. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve prepared a Statement object using createStatement() method. As next step, We”ve prepared a SQL string to drop a table sampledb1 by calling statement.execute() method. Once table is dropped, we”ve printed the status and execute another query to show all the tables in given database and all remaining tables are printed. In case of any exception while connecting to the database, a catch block handled SQLException and printed the stack trace. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.*; // This file demonstrates use of DROP TABLE IF EXISTS command public class JDBCExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “root”; static final String PASS = “guest123”; public static void main(String args[]) { try{ Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); String QUERY = “DROP TABLE IF EXISTS sampledb1”; stmt.execute(QUERY); System.out.println(“Table sampledb1 dropped successfully.”); System.out.println(“—————————————-“); ResultSet rs = stmt.executeQuery(“show tables”); System.out.println(“List of tables”); System.out.println(“—————————————-“); while(rs.next()){ System.out.println(rs.getString(1)); } }catch (SQLException e){ e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac JDBCExample.java C:> When you run JDBCExample, it produces the following result − C:>java JDBCExample Table sampledb1 dropped successfully. —————————————- List of tables —————————————- consumers employees employees_o jdbc_blob_clob officers students C:> Example: Truncate Table DROP TABLE deletes not only all table data, but also table definitions. On the other hand, TRUNCATE TABLE deletes only table data (or rows). TRUNCATE TABLE table_name In this example, we”ve three static strings containing a dababase connection url, username, password. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve prepared a Statement object using createStatement() method. As next step, We”ve prepared a SQL string to query a table sampledb4 by calling statement.executeQuery() method to print all the records. Using result in a ResultSet, we”ve printed all the records. With a new query to truncate the table sampledb4, we”ve truncated the table using execute() method. Now again, we”re fired the select query to get all the records. As resultant resultset is empty, a corresponding message is printed. In case of any exception while connecting to the database, a catch block handled SQLException and printed the stack trace. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.*; public class JDBCExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “root”; static final String PASS = “guest123”; public static void main(String args[]) { try{ Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); String sel_query = “select

JDBC – Stored Procedure

JDBC – Stored Procedure ”; Previous Next We have learnt how to use Stored Procedures in JDBC while discussing the JDBC – Statements chapter. This chapter is similar to that section, but it would give you additional information about JDBC SQL escape syntax. Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure. Creating CallableStatement Object Suppose, you need to execute the following Oracle stored procedure − CREATE OR REPLACE PROCEDURE getEmpName (EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS BEGIN SELECT first INTO EMP_FIRST FROM Employees WHERE ID = EMP_ID; END; NOTE − Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database. DELIMITER $$ DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$ CREATE PROCEDURE `EMP`.`getEmpName` (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255)) BEGIN SELECT first INTO EMP_FIRST FROM Employees WHERE ID = EMP_ID; END $$ DELIMITER ; Three types of parameters exist − IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three. Here are the definitions of each − Parameter Description Example IN A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods. Stored Procedure with only IN parameter OUT A parameter whose value is supplied by the SQL statement it returns. You retrieve values from the OUT parameters with the getXXX() methods. Stored Procedure with only OUT parameter INOUT A parameter that provides both input and output values. You bind variables with the setXXX() methods and retrieve values with the getXXX() methods. Stored Procedure with both IN and OUT parameters The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure − CallableStatement cstmt = null; try { String SQL = “{call getEmpName (?, ?)}”; cstmt = conn.prepareCall (SQL); . . . } catch (SQLException e) { . . . } finally { . . . } The String variable SQL represents the stored procedure, with parameter placeholders. Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException. If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding. When you use OUT and INOUT parameters, you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type the stored procedure is expected to return. Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type. Closing CallableStatement Object Just as you close other Statement object, for the same reason you should also close the CallableStatement object. A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup. CallableStatement cstmt = null; try { String SQL = “{call getEmpName (?, ?)}”; cstmt = conn.prepareCall (SQL); . . . } catch (SQLException e) { . . . } finally { cstmt.close(); } We have studied more details in the Callable – Example Code. JDBC SQL Escape Syntax The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties. The general SQL escape syntax format is as follows − {keyword ”parameters”} Here are the following escape sequences, which you would find very useful while performing the JDBC programming − d, t, ts Keywords They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database”s format. For Example − > {d ”yyyy-mm-dd”} Where yyyy = year, mm = month; dd = date. Using this syntax {d ”2009-09-03”} is March 9, 2009. Here is a simple example showing how to INSERT date in a table − //Create a Statement object stmt = conn.createStatement(); //Insert data ==> ID, First Name, Last Name, DOB String sql=”INSERT INTO STUDENTS VALUES” + “(100,”Zara”,”Ali”, {d ”2001-12-16”})”; stmt.executeUpdate(sql); Similarly, you can use one of the following two syntaxes, either t or ts − {t ”hh:mm:ss”} Where hh = hour; mm = minute; ss = second. Using this syntax {t ”13:30:29”} is 1:30:29 PM. {ts ”yyyy-mm-dd hh:mm:ss”} This is combined syntax of the above two syntax for ”d” and ”t” to represent timestamp. escape Keyword This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example − String sql = “SELECT symbol FROM MathSymbols WHERE symbol LIKE ”%” {escape ””}”; stmt.execute(sql); If you use the backslash character () as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character. fn Keyword This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to

JDBC – RowSet

JDBC – RowSet ”; Previous Next RowSet is an interface, which is like ResultSet, which resides in javax.sql.rowset under java.sql. It inherits from ResultSet, and has more capabilities than a ResultSet. RowSets can be scrollable and updatable. Some DBMS do not support scrollability and updatability of ResultSets. In that case, RowSets have to be used. Also, RowSets have Java Beans functionality. They have properties. Properties can be set or retrieved using setter and getter methods. RowSet uses event model, where events are propagated to when certain events occur. The events are of following three types: Update, insert, or deletion of a row Cursor movement Change in RowSet contents Types of RowSet Interfaces There are 5 major types sub-interfaces of RowSet interface. JdbcRowSet CachedRowSet WebRowSet JoinRowSet FilteredRowSet Example: Performing Basic CRUD operations using RowSet In this example, we”ve three static strings containing a dababase connection url, username, password. Now using RowSetProvider.newFactory().createJdbcRowSet() method, we”ve prepared a JdbcRowSet object as rowSet. In rowSet, we have set url, username, password and a SQL command to get details of employees from employees table. Using rowSet.execute(), the query is fired and records are stored in the rowSet instance. Using rowSet.next() method, we”re checking if more records are present then using getInt() and getString() methods, we”re getting the required values and printing them in a while loop to print all the employees. Using rowSet.absolute(3) method, we”ve moved to third record, and using rowSet.updateInt(), age is marked to be updated as 30. Next using rowSet.updateRow(), the complete record is updated in database. Now using rowSet.last() method, we moved to last record and using rowSet.deleteRow() method, the record is deleted. Now to verify the changes, we”ve set command to select details of employees and execute() it. Finally we”ve printed all the records of the employees again. Copy and paste the following example in RowSetExample.java, compile and run as follows − import javax.sql.rowset.*; import java.sql.*; // This class demonstrates use of basic functionality of rowsets public class RowSetExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “root”; static final String PASS = “guest123”; public static void main(String args[])throws SQLException { JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet(); rowSet.setUrl(DB_URL); rowSet.setUsername(USER); rowSet.setPassword(PASS); rowSet.setCommand(“select id, age, first, last from employees”); rowSet.execute(); while (rowSet.next()) { System.out.print(“Id: ” + rowSet.getInt(“id”)); System.out.print(” Age: ” + rowSet.getInt(“age”)); System.out.print(” First: ” + rowSet.getString(“first”)); System.out.println(” Last: ” + rowSet.getString(“last”)); } System.out.println(“—————————————“); // Position the cursor to the 3rd row rowSet.absolute(3); rowSet.updateInt(“age”,20 ); rowSet.updateRow(); //position the cursor to the last row rowSet.last(); rowSet.deleteRow(); // After updating the 3rd row and deleting the last row, doing a select to view updated records. rowSet.setCommand(“select id, age, first, last from employees”); rowSet.execute(); while (rowSet.next()) { System.out.print(“Id: ” + rowSet.getInt(“id”)); System.out.print(” Age: ” + rowSet.getInt(“age”)); System.out.print(” First: ” + rowSet.getString(“first”)); System.out.println(” Last: ” + rowSet.getString(“last”)); } } } Output Now let us compile the above example as follows − C:>javac RowSetExample.java C:> When you run RowSetExample, it produces the following result − C:>java RowSetExample Id: 1 Age: 18 First: Zara Last: Ali Id: 2 Age: 25 First: Mahnaz Last: Fatma Id: 3 Age: 30 First: Zaid Last: Khan Id: 4 Age: 28 First: Sumit Last: Mittal Id: 7 Age: 20 First: Rita Last: Tez Id: 8 Age: 20 First: Sita Last: Singh Id: 21 Age: 35 First: Jeevan Last: Rao Id: 22 Age: 40 First: Aditya Last: Chaube Id: 25 Age: 35 First: Jeevan Last: Rao Id: 26 Age: 35 First: Aditya Last: Chaube Id: 34 Age: 45 First: Ahmed Last: Ali Id: 35 Age: 50 First: Raksha Last: Agarwal Id: 36 Age: 50 First: Sankalp Last: Hawladar Id: 37 Age: 50 First: Anand Last: Roy ————————————— Id: 1 Age: 18 First: Zara Last: Ali Id: 2 Age: 25 First: Mahnaz Last: Fatma Id: 3 Age: 20 First: Zaid Last: Khan Id: 4 Age: 28 First: Sumit Last: Mittal Id: 7 Age: 20 First: Rita Last: Tez Id: 8 Age: 20 First: Sita Last: Singh Id: 21 Age: 35 First: Jeevan Last: Rao Id: 22 Age: 40 First: Aditya Last: Chaube Id: 25 Age: 35 First: Jeevan Last: Rao Id: 26 Age: 35 First: Aditya Last: Chaube Id: 34 Age: 45 First: Ahmed Last: Ali Id: 35 Age: 50 First: Raksha Last: Agarwal Id: 36 Age: 50 First: Sankalp Last: Hawladar C:> Event Handling in RowSet Operations There is an interface RowSetListener which needs to be added to JdbcRowSet via addRowSetListener. There are three methods in RowSetListener that needs to be implemented. public void cursorMoved(RowSetEvent event) This method is trigerred on RowSet cursor movement. public void rowChanged(RowSetEvent event) This is trigerred when a row in a RowSet has changed. public void rowSetChanged(RowSetEvent event); This is trigerred when the entire contents of RowSet changed. Example: Handling of events in RowSet Operations with Listeners In this example, we”ve three static strings containing a dababase connection url, username, password. Now using RowSetProvider.newFactory().createJdbcRowSet() method, we”ve prepared a JdbcRowSet object as rowSet. In rowSet, we have set url, username, password and a SQL command to get details of employees from employees table. Using rowSet.execute(), the query is fired and records are stored in the rowSet instance. We”ve defined a RowSetListener as CustomListener which listens to various RowSetEvent. Using rowSet.addRowSetListener(), this listener is registered with the rowSet. Using rowSet.next() method, we”re checking if more records are present then using getInt() and getString() methods, we”re getting the required values and printing them in a while loop to print all the employees. Using rowSet.absolute(3) method, we”ve moved to third record, and using rowSet.updateInt(), age is marked to be updated as 30. Next using rowSet.updateRow(), the complete record is

JDBC – Streaming Data

JDBC – Streaming ASCII and Binary Data ”; Previous Next A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can hold large values, such as CLOB and BLOB data types. There are following methods, which can be used to stream data − setAsciiStream() − This method is used to supply large ASCII values. setCharacterStream() − This method is used to supply large UNICODE values. setBinaryStream() − This method is used to supply large binary values. The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream. Using setAsciiStream() to store Ascii Value in database Example This example would create a database table XML_Data and then XML content would be written into this table. In this program, we”ve defined few static strings for database connection, username, password and for queries. One query is to select data from table XML_Data, one query is to insert data into XML_data table, one query is to create the XML_Data table and one query is to drop the table. One string contains xml data to be stored in the table. Using createXMLTable() method, we”re first droping the table and then creating it. In main method, using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve created a Statement object using connection.createStatement() method and a PreparedStatement object using connection.prepareStatement() method. createXMLTable() method is called to create the XML_Data table. A ByteArrayInputStream object is created with static XML string. Using PreparedStatement.setAsciiStream() method, that byte stream is stored in preparedStatement. Using preparedStatement.execute() method, byte stream is stored in database. Using statement.executeQuery() method, the select query is fired and result is stored in a result set. Result Set is iterated and using getAsciiStream(), the ascii stream is retrieved as input stream and using ByteArrayInputStream.toString(), this stream is printed to the console. Copy and paste the following example in TestApplication.java, compile and run as follows − import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; static final String QUERY = “SELECT Data FROM XML_Data WHERE id=100″; static final String INSERT_QUERY=”INSERT INTO XML_Data VALUES (?,?)”; static final String CREATE_TABLE_QUERY = “CREATE TABLE XML_Data (id INTEGER, Data LONG)”; static final String DROP_TABLE_QUERY = “DROP TABLE XML_Data”; static final String XML_DATA = “<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>”; public static void createXMLTable(Statement stmt) throws SQLException{ System.out.println(“Creating XML_Data table…” ); //Drop table first if it exists. try{ stmt.executeUpdate(DROP_TABLE_QUERY); }catch(SQLException se){ } stmt.executeUpdate(CREATE_TABLE_QUERY); } public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY); ) { createXMLTable(stmt); ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes()); pstmt.setInt(1,100); pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length); pstmt.execute(); //Close input stream bis.close(); ResultSet rs = stmt.executeQuery(QUERY); // Get the first row if (rs.next ()){ //Retrieve data from input stream InputStream xmlInputStream = rs.getAsciiStream (1); int c; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (( c = xmlInputStream.read ()) != -1) bos.write(c); //Print results System.out.println(bos.toString()); } // Clean-up environment rs.close(); } catch (SQLException | IOException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac TestApplication.java C:> When you run TestApplication, it produces the following result − C:>java TestApplication Creating XML_Data table… <Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee> C:> Using setBinaryStream() to store Binary Value in database Example In this example, we”re using JDBC_BLOB_CLOB table created in JDBC – Data Types chapter. In this program, we”ve defined few static strings for database connection, username, password and a query to insert binary image into the table. In main method, using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve created a PreparedStatement object using connection.prepareStatement() method. To get image stream, we”ve used FileInputStream to read the image file from the File System and using PreparedStatement.setBinaryStream(), the stream is stored in the preparedStatement object. Using executeUpdate(), the image is stored in the table. Using connection.createStatement() method, a statement is created to get the image data from the database table. Using executeQuery(), the select query is fired and result is stored in a result set. ResultSet is iterated and using getBinaryStream(), an inputstream object is retrieved which is then used to store the data in a byte array. The byte array is then stored in a File using FileOutputStream and result is displayed. import java.sql.*; import java.io.*; //This class demonstrates use of setBinaryStream public class BinaryStreamExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123″; static final String QUERY = ” INSERT INTO jdbc_blob_clob (name, image) VALUES (?, ?);”; public static void main(String args[]) { Connection conn = null; PreparedStatement pstmt = null; Statement stmt = null; try{ conn = DriverManager.getConnection(DB_URL,USER,PASS); System.out.println(“Connection to db established.”); File image = new File(“C:\Users\Saikat\OneDrive\Documents\saikat_upwork1.jpg”); pstmt = conn.prepareStatement(QUERY); FileInputStream fis = new FileInputStream(image); pstmt.setString(1, “TutorialsPoint”); pstmt.setBinaryStream(2, fis ); pstmt.executeUpdate(); fis.close(); System.out.println(“Successfully inserted image in db”); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(“select name, image from jdbc_blob_clob where name=”TutorialsPoint””); if (rs.next()) { InputStream ins = rs.getBinaryStream(“image”); byte byteArray[] = new byte[ins.available()]; ins.read(byteArray); String filePath = “C:\Users\Saikat\output_saikat_upwork1.jpg”; FileOutputStream outPutStream = new FileOutputStream(filePath); outPutStream.write(byteArray); outPutStream.close(); System.out.println(“Binary image successfully stored at: “+ filePath); } pstmt.close(); conn.close(); } catch(IOException ioe){ ioe.printStackTrace(); } catch(SQLException e){ e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac BinaryStreamExample.java C:> When you run BinaryStreamExample, it produces the following result − C:>java BinaryStreamExample

JDBC – Sample Code

JDBC – Sample, Example Code ”; Previous Next This chapter provides an example of how to create a simple JDBC application. This will show you how to open a database connection, execute a SQL query, and display the results. All the steps mentioned in this template example, would be explained in subsequent chapters of this tutorial. Creating JDBC Application There are following six steps involved in building a JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database. Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set. Clean up the environment − Requires explicitly closing all database resources versus relying on the JVM”s garbage collection. Sample Code to Select Records This sample example can serve as a template when you need to create your own JDBC application in the future. This sample code has been written based on the environment and database setup done in the previous chapter. In this example, we”ve four static strings containing a dababase connection url, username, password and a SELECT query. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve created a Statement object using connection.createStatement() method, then using statement.executeQuery(), the SELECT Query is executed and result is stored in a resultset. Now resultset is iterated and each record is printed. Copy and paste the following example in SelectExample.java, compile and run as follows − import java.sql.*; public class SelectExample { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; static final String QUERY = “SELECT id, first, last, age FROM Employees”; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(QUERY);) { // Extract data from result set while (rs.next()) { // Retrieve by column name System.out.print(“ID: ” + rs.getInt(“id”)); System.out.print(“, Age: ” + rs.getInt(“age”)); System.out.print(“, First: ” + rs.getString(“first”)); System.out.println(“, Last: ” + rs.getString(“last”)); } } catch (SQLException e) { e.printStackTrace(); } } } Output Now let us compile the above example as follows − C:>javac SelectExample.java C:> When you run SelectExample, it produces the following result − C:>java SelectExample Connecting to database… Creating statement… ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:> Sample Code to Update Records In this example, we”ve five static strings containing a dababase connection url, username, password, UPDATE Query and a SELECT query. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve created a Statement object using connection.createStatement() method. Now using statement.executeUpdate(), we”ve run the update query. Lastly using statement.executeQuery(), the SELECT Query is executed and result is stored in a resultset. Now resultset is iterated and each record is printed to check the updated content. Copy and paste the following example in UpdateExample.java, compile and run as follows − import java.sql. *; public class UpdateExample { static final String DB_URL = “jdbc: mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; static final String QUERY1 = “UPDATE Employees SET age=20 where id=100”; static final String QUERY2= “SELECT id, first, last, age FROM Employees”; public static void main (String [] args) { // Open a connection try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { stmt.executeUpdate(QUERY1); ResultSet rs=stmt.executeQuery(QUERY2); // Extract data from result set while (rs.next()) { // Retrieve by column name System.out.print(“ID: ” + rs.getInt(“id”)); System.out.print(“, Age: ” + rs.getInt(“age”)); System.out.print(“, First: ” + rs.getString(“first”)); System.out.println(“, Last: ” + rs.getString(“last”)); } } catch (SQLException e) { e.printStackTrace(); } } } Output Now let us compile the above example as follows − C:>javac UpdateExample.java C:> When you run UpdateExample, it produces the following result − C:>java UpdateExample ID: 100, Age: 20, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:> Sample Code to Delete Records In this example, we”ve five static strings containing a dababase connection url, username, password, Delete Query and a SELECT query. Now using DriverManager.getConnection() method, we”ve prepared a database connection. Once connection is prepared, we”ve created a Statement object using connection.createStatement() method. Now using statement.executeUpdate(), we”ve run the delete query. Lastly using statement.executeQuery(), the SELECT Query is executed and result is stored in a resultset. Now resultset is iterated and each record is printed to check the deleted content. Copy and paste the following example in DeleteExample.java, compile and run as follows − import java.sql. *; public class DeleteExample { static final String DB_URL = “jdbc: mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; static final String QUERY1 = “DELETE from Employees where id=100”; static final String QUERY2= “SELECT id, first, last, age FROM Employees”; public static void main (String [] args) { // Open a connection try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { stmt.executeUpdate(QUERY1); ResultSet rs=stmt.executeQuery(QUERY2); // Extract data from result set while (rs.next()) { // Retrieve by column name System.out.print(“ID: ” + rs.getInt(“id”)); System.out.print(“, Age: ” + rs.getInt(“age”)); System.out.print(“, First:

JDBC – Data Types

JDBC – Data Types ”; Previous Next The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency between drivers. The following table summarizes the default JDBC data type that the Java data type is converted to, when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method. SQL vs Java Data Types SQL JDBC/Java setXXX updateXXX VARCHAR java.lang.String setString updateString CHAR java.lang.String setString updateString LONGVARCHAR java.lang.String setString updateString BIT boolean setBoolean updateBoolean NUMERIC java.math.BigDecimal setBigDecimal updateBigDecimal TINYINT byte setByte updateByte SMALLINT short setShort updateShort INTEGER int setInt updateInt BIGINT long setLong updateLong REAL float setFloat updateFloat FLOAT float setFloat updateFloat DOUBLE double setDouble updateDouble VARBINARY byte[ ] setBytes updateBytes BINARY byte[ ] setBytes updateBytes DATE java.sql.Date setDate updateDate TIME java.sql.Time setTime updateTime TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp CLOB java.sql.Clob setClob updateClob BLOB java.sql.Blob setBlob updateBlob ARRAY java.sql.Array setARRAY updateARRAY REF java.sql.Ref SetRef updateRef STRUCT java.sql.Struct SetStruct updateStruct XML SQLXML setSQLXML updateSQLXML ROWID RowId setRowId updateRowId DISTINCT BigDecimal setBigDecimal updateBigDecimal DATALINK Java.netURL setURL updateURL NCLOB NClob setNClob updateNClob JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to directly manipulate the respective data on the server. The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to a JDBC data type. ResultSet object provides corresponding getXXX() method for each data type to retrieve column value. Each method can be used with column name or by its ordinal position. ResultSet Methods to Get/Set SQL Values SQL JDBC/Java setXXX getXXX VARCHAR java.lang.String setString getString CHAR java.lang.String setString getString LONGVARCHAR java.lang.String setString getString BIT boolean setBoolean getBoolean NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal TINYINT byte setByte getByte SMALLINT short setShort getShort INTEGER int setInt getInt BIGINT long setLong getLong REAL float setFloat getFloat FLOAT float setFloat getFloat DOUBLE double setDouble getDouble VARBINARY byte[ ] setBytes getBytes BINARY byte[ ] setBytes getBytes DATE java.sql.Date setDate getDate TIME java.sql.Time setTime getTime TIMESTAMP java.sql.Timestamp setTimestamp getTimestamp CLOB java.sql.Clob setClob getClob BLOB java.sql.Blob setBlob getBlob ARRAY java.sql.Array setARRAY getARRAY REF java.sql.Ref SetRef getRef STRUCT java.sql.Struct SetStruct getStruct XML SQLXML setSQLXML getSQLXML ROWID RowId setRowId getRowId DISTINCT BigDecimal setBigDecimal getBigDecimal DATALINK Java.netURL setURL getURL NCLOB NClob setNClob getNClob Date & Time Data Types The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data types, respectively. Getting Current Time from Java Util Date and Java SQL Date Objects Example Following example shows how the Date and Time classes format the standard Java date and time values to match the SQL data type requirements. package com.tutorialspoint; public class SqlDateTime { public static void main(String[] args) { //Get standard date and time java.util.Date javaDate = new java.util.Date(); long javaTime = javaDate.getTime(); System.out.println(“The Java Date is:” + javaDate.toString()); //Get and display SQL DATE java.sql.Date sqlDate = new java.sql.Date(javaTime); System.out.println(“The SQL DATE is: ” + sqlDate.toString()); //Get and display SQL TIME java.sql.Time sqlTime = new java.sql.Time(javaTime); System.out.println(“The SQL TIME is: ” + sqlTime.toString()); //Get and display SQL TIMESTAMP java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(javaTime); System.out.println(“The SQL TIMESTAMP is: ” + sqlTimestamp.toString()); }//end main }//end SqlDateTime Output Now let us compile the above example as follows − C:>javac SqlDateTime.java C:> When you run SqlDateTime, it produces the following result − C:>java SqlDateTime The Java Date is:Fri Jun 07 09:38:32 IST 2024 The SQL DATE is: 2024-06-07 The SQL TIME is: 09:38:32 The SQL

JDBC – Environment

JDBC – Environment Setup ”; Previous Next To start developing with JDBC, you should setup your JDBC environment by following the steps shown below. We assume that you are working on a Windows platform. Install Java Java SE is available for download for free. To download click here, please download a version compatible with your operating system. Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories. Setting Up the Path for Windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory − Right-click on ”My Computer” and select ”Properties”. Click on the ”Environment variables” button under the ”Advanced” tab. Now, edit the ”Path” variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:WindowsSystem32, then edit it the following way C:WindowsSystem32;c:Program Filesjavajdkbin Setting Up the Path for Windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory − Edit the ”C:autoexec.bat” file and add the following line at the end − SET PATH = %PATH%;C:Program Filesjavajdkbin Setting Up the Path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc − export PATH = /path/to/java:$PATH” You automatically get both JDBC packages java.sql and javax.sql, when you install J2SE Development Kit. Install Database The most important thing you will need, of course is an actual running database with a table that you can query and modify. Install a database that is most suitable for you. You can have plenty of choices and most common are − MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Workbench which is a GUI based tool that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:Program FilesMySQLmysql-connector-j-8.4.0. Accordingly, set CLASSPATH variable to C:Program FilesMySQLmysql-connector-j-8.4.0mysql-connector-java-8.4.0.jar. Your driver version may vary based on your installation. Set Database Credential When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice. Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123 as password. If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you. Create Database To create the TUTORIALSPOINT database, use the following steps − Step 1 Open a Command Prompt and change to the installation directory as follows − C:> C:>cd Program FilesMySQLbin C:Program FilesMySQLbin> Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server. Step 2 Start the database server by executing the following command, if it is already not running. C:Program FilesMySQLbin>mysqld C:Program FilesMySQLbin> Step 3 Create the TUTORIALSPOINT database by executing the following command − C:Program FilesMySQLbin> mysqladmin create TUTORIALSPOINT -u guest -p Enter password: ******** C:Program FilesMySQLbin> Create Table To create the Employees table in TUTORIALSPOINT database, use the following steps − Step 1 Open a Command Prompt and change to the installation directory as follows − C:> C:>cd Program FilesMySQLbin C:Program FilesMySQLbin> Step 2 Login to the database as follows − C:Program FilesMySQLbin>mysql -u guest -p Enter password: ******** mysql> Step 3 Create the table Employees as follows − mysql> use TUTORIALSPOINT; mysql> create table Employees -> ( -> id int not null, -> age int not null, -> first varchar (255), -> last varchar (255) -> ); Query OK, 0 rows affected (0.08 sec) mysql> Create Data Records Finally you create few records in Employee table as follows − mysql> INSERT INTO Employees VALUES (100, 18, ”Zara”, ”Ali”); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, ”Mahnaz”, ”Fatma”); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, ”Zaid”, ”Khan”); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, ”Sumit”, ”Mittal”); Query OK, 1 row affected (0.00 sec) mysql> For a complete understanding on MySQL database, study the MySQL Tutorial. Now you are ready to start experimenting with JDBC. Next chapter gives you a sample example on JDBC Programming. Print Page Previous Next Advertisements ”;

JDBC – SQL Syntax

JDBC – SQL Syntax ”; Previous Next Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries. SQL is supported by almost any database you will likely use, and it allows you to write database code independently of the underlying database. This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts. After going through this chapter, you will be able to Create, Create, Read, Update, and Delete (often referred to as CRUD operations) data from a database. For a detailed understanding on SQL, you can read our MySQL Tutorial. Create Database The CREATE DATABASE statement is used for creating a new database. The syntax is − SQL> CREATE DATABASE DATABASE_NAME; Example The following SQL statement creates a Database named EMP − SQL> CREATE DATABASE EMP; Drop Database The DROP DATABASE statement is used for deleting an existing database. The syntax is − SQL> DROP DATABASE DATABASE_NAME; Example The following SQL statement creates a Database named EMP − SQL> DROP DATABASE EMP; Note − To create or drop a database you should have administrator privilege on your database server. Be careful, deleting a database would loss all the data stored in the database. Create Table The CREATE TABLE statement is used for creating a new table. The syntax is − SQL> CREATE TABLE table_name ( column_name column_data_type, column_name column_data_type, column_name column_data_type … ); Example The following SQL statement creates a table named Employees with four columns − SQL> CREATE TABLE Employees ( id INT NOT NULL, age INT NOT NULL, first VARCHAR(255), last VARCHAR(255), PRIMARY KEY ( id ) ); Drop Table The DROP TABLE statement is used for deleting an existing table. The syntax is − SQL> DROP TABLE table_name; Example The following SQL statement deletes a table named Employees − SQL> DROP TABLE Employees; INSERT Data The syntax for INSERT, looks similar to the following, where column1, column2, and so on represents the new data to appear in the respective columns − SQL> INSERT INTO table_name VALUES (column1, column2, …); Example The following SQL INSERT statement inserts a new row in the Employees database created earlier − SQL> INSERT INTO Employees VALUES (100, 18, ”Zara”, ”Ali”); SELECT Data The SELECT statement is used to retrieve data from a database. The syntax for SELECT is − SQL> SELECT column_name, column_name, … FROM table_name WHERE conditions; The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators. Example The following SQL statement selects the age, first and last columns from the Employees table, where id column is 100 − SQL> SELECT first, last, age FROM Employees WHERE id = 100; The following SQL statement selects the age, first and last columns from the Employees table where first column contains Zara − SQL> SELECT first, last, age FROM Employees WHERE first LIKE ”%Zara%”; UPDATE Data The UPDATE statement is used to update data. The syntax for UPDATE is − SQL> UPDATE table_name SET column_name = value, column_name = value, … WHERE conditions; The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators. Example The following SQL UPDATE statement changes the age column of the employee whose id is 100 − SQL> UPDATE Employees SET age=20 WHERE id=100; DELETE Data The DELETE statement is used to delete data from tables. The syntax for DELETE is − SQL> DELETE FROM table_name WHERE conditions; The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators. Example The following SQL DELETE statement deletes the record of the employee whose id is 100 − SQL> DELETE FROM Employees WHERE id=100; Print Page Previous Next Advertisements ”;

JDBC – Driver Types

JDBC – Driver Types ”; Previous Next 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. Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful. Type 4 − 100% Pure Java In a Type 4 driver, a pure Java-based driver communicates directly with the vendor”s database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. This kind of driver is extremely flexible, you don”t need to install special software on the client or server. Further, these drivers can be downloaded dynamically. MySQL”s Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. Which Driver should be Used? If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4. If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver. Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database. The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only. Print Page Previous Next Advertisements ”;