Skip to main content

Prepare Statement

Prepare Statement :

  • PrepareStatement is an interface in java.
  • Object of Prepare Statement help us to execute Dynamic SQL
    query.

Dynamic SQL query :

  •  It must have condition and one or more condition value get
    decided at run time.
  • i.e.

    1. SELECT *FROM student_detail WHERE user_id=? ;
    
    2. INSERT INTO student_detail VALUES(?,?,?) ;
    
How to Pass Command line argument in Eclipse ?
step 1: click on run arrow beside run button

run-config
step 2: Go to main and select appropriate Project and Main class

runc

step:3 Open argument and give value
note: if you want to pass multiple argument then separate it using space.

runc2

Program to Fetch data from database using Prepare statement object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
 
package com.spy.javaforlearn;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import  com.mysql.jdbc.Driver;//Driver class
 
public class PrepareStatement1
{
	public static void main(String[] args)
	{
 
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try
		{
 
		//1.Load the Driver
 
		Driver driverref=new Driver();
		DriverManager.registerDriver(driverref);
 
        //get the db connection via driver
 
	String dburl="jdbc:mysql://localhost:3306/test?user=root&password=root";
	con=DriverManager.getConnection(dburl);
 
		//issue sql query
 
 
	       //dynamic SQL
                String query="Select *from Student_detail where user_id=?";
		pstmt=con.prepareStatement(query);
		pstmt.setString(1, args[0]);//assigning command line arg
		rs=pstmt.executeQuery();
 
		//process result return by mysql query
 
		while(rs.next())
		{
			String id=rs.getString("user_id");
			String f_name=rs.getString("f_name");
			String l_name=rs.getString("l_name");
 
 
			System.out.println("user_id:"+id);
			System.out.println("first name:"+f_name);
			System.out.println("last name:"+l_name);
		}
	     }
		catch(Exception e)
		 {
			e.printStackTrace();
		 }
 
		finally
		{
			try
			{
 
			  if(con!=null)
 
			   {
			     con.close();
 
			   }
 
	 	      if(pstmt!=null)
		      {
		     	pstmt.close();
		      }
 
		      if(rs!=null)
		      {
			     rs.close();
		      }
 
		     }
 
	              catch(Exception e)
		      {
		       System.out.println("Exception occur");   
		      }
 
	 	 }
	   }				
     }
 
output:
user_id:2
first name:vivel
last name:patel