3:53 pm - Friday March 24, 4772

Statement SELECT Example program in java Jdbc mysql database

Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

Select statement:

This tutorial explains how to fetch or retrieve all row in a table in mysql using java statement example, Load the mysql driver using Class.forName method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and use executeQuery to execute the query and use a resultset object to hold the data as java object.  If we wants to add a new  record into the table or to add a new row, just use this following code to update the table with new record.

create table:

     mysql> create table student(Roll_No int(5),Name varchar(25),

Department varchar(7),Address varchar(30));

Query OK, 0 rows affected (0.06 sec)


Java code:

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

public class Select {

	 * @param args
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String Driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost/test";
		String uName ="root";
		String pwd = "root";
		Connection conn=null;

		try {
			conn = DriverManager.getConnection(url, uName, pwd);
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM student");
			System.out.println("select statement sucessfully used");
			while (rs.next()) {
				String Roll_no= rs.getString("Roll_no");
				String name= rs.getString("name");
				String department= rs.getString("department");
				String address= rs.getString("address");
				System.out.print(Roll_no+ "\t");
				System.out.print(name+ "\t");
				System.out.print(department+ "\t");
				System.out.println( address+ "\t");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
		catch (SQLException e) {
			// TODO Auto-generated catch block
		catch (Exception e) {
			// TODO Auto-generated catch block
			try {
			} catch (SQLException e) {
				// TODO Auto-generated catch block




select statement sucessfully used:

101   suresh      cse   dharmapuri

103   arivu       AE    trichy

104   muthu       ECE   ariyalur

105   mani        EEE   kovai

106   tamil       CSE   trichy

107   Raja        IT    tanjur      

Filed in: Z-A All Java Codes

Comments are closed.