Share on Google+Share on Google+

JDBC executeUpdate() And executeQuery()

In this tutorial you will learn about executeQuery(), and executeUpdate() mehod

Statement executeQuery() and executeUpdate() Example

executeQuery() method is used mostly for SELECT statement and it returns the in form of ResultSet object.

executeUpdate() method is generally used by INSERT, UPDATE,  And DELETE statements. When table updated successfully then it returns 1.

An example given below illustrates the use of these methods


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

public class JDBCEexecuteExample {
	public static void main(String[] args) throws SQLException {
		Connection connection = null; // connection reference variable for
										// getting
		// connection
		Statement statement = null; // Statement reference variable for query
		// Execution
		ResultSet resultSet = null; // ResultSet reference variable for saving
									// query
		// result
		String conUrl = "jdbc:mysql://localhost:3306/";
		String driverName = "com.mysql.jdbc.Driver";
		String databaseName = "student";
		String usrName = "root";
		String usrPass = "root";
		try {
			// Loading Driver
		} catch (ClassNotFoundException e) {
		try {
			// Getting Connection
			connection = DriverManager.getConnection(conUrl + databaseName,
					usrName, usrPass);
			// setting connection autocommit false
			// Getting reference to connection object
			statement = connection.createStatement();
			// creating Query String
			String updateQuery = "UPDATE student SET NAME='Rajan' WHERE RollNo=1";
			String selectQuery = "SELECT * FROM student";
			String insertQuery = "INSERT INTO student values(4,'Rohan','MCA','Mumbai')";
			String deleteQuery = "DELETE FROM student WHERE RollNo=4";
			// Insert Query
			// Updating Query
			int result = statement.executeUpdate(updateQuery);
			if (result == 1) {
				System.out.println("Table Updated Successfully.......");
			// Delete Query
			// excecuting query
			resultSet = statement.executeQuery(selectQuery);
			while ( {
				// Didplaying data of tables
				System.out.println("Roll No " + resultSet.getInt("RollNo")
						+ ", Name " + resultSet.getString("Name") + ", Course "
						+ resultSet.getString("Course") + ", Address "
						+ resultSet.getString("Address"));
		} catch (Exception e) {
		} finally {
			// Closing connection
When you run this application it will display message as shown below:

Table Updated Successfully.......
Roll No 1, Name Rajan, Course MCA, Address Motihari
Roll No 3, Name Rohan, Course MCA, Address Mumbai

Download this example code


Posted on: October 21, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.