Share on Google+Share on Google+

JDBC Select All Records Example

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 "" 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    "" 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;
		con = DriverManager.getConnection(url+dbName, userName, password);
		   stmt = con.createStatement();
		   String query = "SELECT * FROM user";
		   ResultSet rs=stmt.executeQuery(query);
		   //Extact result from ResultSet rs
		   // close ResultSet rs
		   } catch(SQLException s){						
		// close Connection and Statement
		}catch (Exception e){

Program Output:


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


Download Code


Posted on: October 15, 2010 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.