Home Tutorial Java Jdbc Mysql JDBC Select All Records Example

 
 

JDBC Select All Records Example
Posted on: October 15, 2010 at 12:00 AM
Advertisement
In this tutorial we will learn how select all records from the table use mysql JDBC driver.

JDBC Select All Records Example

In this tutorial we will learn how select all records from the table use mysql JDBC driver. This tutorial example  for select  all records from table if exist and defined how the records fetch and store.

This example applied mysql query "SELECT * FROM user" and  applied  the given step by step that describe in "SelectAllRecords.java" class and given steps as:

1.Import the packages
2.Register the JDBC driver
3.Open a connection
4.Execute a query
5.Extract Data   

                 First  we create connection to the database server, again create  query  and execute , store the  result  in  ResultSet object  and  Extract data. While loop extract data from ResultSet  rs one by one row and print also. The  code of    "SelectAllRecords.java" given below : 

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
  
public class SelectAllRecords{
 // JDBC driver name and database URL
 static String driverName = "com.mysql.jdbc.Driver";
 static String url = "jdbc:mysql://localhost:3306/";

 // defined and set value in  dbName, userName and password variables
 static String dbName = "testjdbc";
 static String userName = "root";
 static String password = "";
	
 public static void main(String[] args){
	// create Connection con, and Statement stmt 
	Connection con=null;
	Statement stmt=null;
	try{
		Class.forName(driverName).newInstance();
		con = DriverManager.getConnection(url+dbName, userName, password);
		try{
		   stmt = con.createStatement();
		   String query = "SELECT * FROM user";
		   ResultSet rs=stmt.executeQuery(query);
		   System.out.println("user_id"+"\t"+"user_name");
		   //Extact result from ResultSet rs
		   while(rs.next()){
				 System.out.println(""+rs.getInt("user_id")+"\t"+rs.getString("user_name"));				
			  }
		   // close ResultSet rs
		   rs.close();
		   } catch(SQLException s){						
				s.printStackTrace();
			 }
		// close Connection and Statement
		con.close();
		stmt.close();
		}catch (Exception e){
			e.printStackTrace();
		 }
  }
}

Program Output:

F:\jdbc>javac SelectAllRecords.java

F:\jdbc>java SelectAllRecords
user_id user_name
1          User1
2          User2
3          User3
4          User4
5          User5

F:\jdbc>

Download Code

Advertisement

Related Tags for JDBC Select All Records Example:


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.

Posted on: October 15, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com