Share on Google+Share on Google+

JDBC: Select Records using Prepared Statement

Advertisement
In this section, you will learn how to retrieve records of table using Prepared Statement.

JDBC: Select Records using Prepared Statement

In this section, you will learn how to retrieve records of table using Prepared Statement.

Select Records   :

Prepared Statement is precompiled SQL Statements which are stored in a PreparedStatement object and you can use this object to execute this statement many times. It is the best way to reduce execution time and improve performance.
JDBC API provides a simple way to handle the database and execute the common sql query. Select statement is used to retrieve records from the table and display on your console.

Example : In this example we are retrieving records from the student table whose roll no is less than 10.

package jdbc;

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

class PreparedStatementSelect {
	public static void main(String[] args) {
		System.out.println("Select Records using PreparedStatement...");
		Connection con = null;
		PreparedStatement statement = null;
		ResultSet rs = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			Class.forName(driverName);

			// Connecting to the database
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {

				// Selecting records
				String sql = "SELECT * FROM student WHERE roll_no < ?";
				statement = con.prepareStatement(sql);
				statement.setInt(1, 10);
				rs = statement.executeQuery();
				System.out.println("RollNo\tName\tCourse\tLocation");
				System.out.println("---------------------------------");
				while (rs.next()) {
					int roll = rs.getInt("roll_no");
					String name = rs.getString("name");
					String course = rs.getString("course");
					String location = rs.getString("location");
					System.out.println(roll + "\t" + name + "\t" + course
							+ "\t" + location);
				}

			} catch (SQLException e) {
				System.out.println(e);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Select Records using PreparedStatement...
RollNo	Name	Course	Location
---------------------------------
1	Ron	MTech	Sparta
2	Mandy	BCA	Phoneix
3	Julu	MCA	Singapore
4	Andru	BCA	Perth
6	Linda	BCA	NewYork
7	Lori	MTech	Kolkata
9	Jackson	MBA	London

Advertisements

Posted on: October 3, 2012 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.