Executing Prepared Statement


 

Executing Prepared Statement

In this tutorial you will learn how to execute query in JDBC prepared statement,

In this tutorial you will learn how to execute query in JDBC prepared statement,

Executing Prepared Statement

Prepared Statement represents the pre-compiled query with parameter and no-parameter. An example given below is no-parameter prepared statement example.

Example-

At first create table named student in MySql database and inset values into it as.

CREATE TABLE student (
RollNo int(9)  PRIMARY KEY NOT NULL,
Name tinytext NOT NULL,
Course varchar(25) NOT NULL,
Address text
 );

Inset Data into the student table

PreparedStatementExecuteExample.java

package roseindia.net;

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

public class PreparedStatementExecuteExample {
	Connection connection = null;
	String driverName = "com.mysql.jdbc.Driver";
	String connectionUrl = "jdbc:mysql://localhost:3306/student";
	String userName = "root";
	String userPass = "root";

	public PreparedStatementExecuteExample() {
		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			System.out.println(e.toString());
		}
	}

	public Connection getConnection() {
		try {
			connection = DriverManager.getConnection(connectionUrl, userName,
					userPass);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}

	public static void main(String[] args) throws SQLException {
		PreparedStatementExecuteExample ptmtExample = new PreparedStatementExecuteExample();
		Connection con = ptmtExample.getConnection();
		// Writing a query
		String query = "SELECT * FROM student";
		try {
			// Compiling query String
			PreparedStatement statement = con.prepareStatement(query);
			ResultSet resultSet=statement.executeQuery();
			while(resultSet.next()){
				System.out.println("Roll No- "+resultSet.getInt(1)+", Name- "+resultSet.getString(2)+", Course- "+resultSet.getString(3)+", Address- "+resultSet.getString(4));
			}
			statement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			con.close();
		}
	}
}
When you run this application it will display message as shown below:

Roll No- 1, Name- Rajan, Course- MCA, Address- Motihari
Roll No- 2, Name- Dinesh, Course- MCA, Address- Patna
Roll No- 3, Name- Rohan, Course- MCA, Address- Mumbai
Roll No- 4, Name- Ramesh, Course- B.Tech, Address- Nagpurs

Download this example code

Ads