Home Tutorial Java Jdbc Mysql JDBC Select Record Example

 
 

Share on Google+Share on Google+
JDBC Select Record Example
Posted on: October 15, 2010 at 12:00 AM
Advertisement
In this tutorial we will learn how select specific record from table use mysql JDBC driver.

JDBC Select Record Example

 In this tutorial we will learn how select specific  record from table use mysql JDBC driver. This  select the one or more row records that follow specific condition i.e user_id=1 or user_name="User1" etc. This  tutorial use the mysql  query  "SELECT * FROM user WHERE  user_id=1"  , if   use the  another condition  i.e user_name="User1" then fetch the all records that user_name="User1". Table given below as :             

     

If Change  mysql  query "SELECT * FROM user  WHERE  user_user='User1' " , then   fetch all row record that user_name =User1.The code of   "SelectRecord.java"  class is: 

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
  
public class SelectRecord{
 // 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 WHERE  user_id=1";
		  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 SelectRecord.java

F:\jdbc>java SelectRecord
user_id user_name
1           User1

F:\jdbc>

Download Code

Advertisement

Related Tags for JDBC Select Record 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