JDBC Select Statement Example


 

JDBC Select Statement Example

In this tutorial you will learn how to connect to the database execute select statemet query from table.

In this tutorial you will learn how to connect to the database execute select statemet query from table.

JDBC Select Statement Example

Select Statement retieves the data from single or multiple tables from a database. The result is Returned to ResultSet object, this ResultSet object is used to display the result. To process each row of the table next() method of ResultSet is used.

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
 );

Insert Value Into student table

INSERT INTO student VALUES(1, 'Ram', 'B.Tech', 'Delhi') ;

JDBCSelectExample.java

package roseindia.net;

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

public class JDBCSelectExample {
	public static void main(String[] args) throws SQLException {
		Connection con = null; // connection reference variable for getting
		// connection
		Statement stmt = null; // Statement reference variable for query
		// Execution
		ResultSet rs = 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
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			System.out.println(e.toString());
		}
		try {
			// Getting Connection
			con = DriverManager.getConnection(conUrl + databaseName, usrName,
					usrPass);
			// Creating Statement for query execution
			stmt = con.createStatement();
			// creating Query String
			String query = "SELECT * FROM student";
			// excecuting query
			rs = stmt.executeQuery(query);
			while (rs.next()) {
				// Didplaying data of tables
				System.out.println("Roll No " + rs.getInt("RollNo") + ", Name "
						+ rs.getString("Name") + ", Course "
						+ rs.getString("Course") + ", Address "
						+ rs.getString("Address"));
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			// Closing connection
			con.close();
			stmt.close();
			rs.close();
		}
	}
}
When you run this application it will display message as shown below:

Roll No 1, Name Ram, Course B.Tech, Address Delhi

Download this example code

Ads