Skip to main content

Statement object in JDBC

Statement Object

  • Statement object is an interface of java.sql.* package
  •  It is used execute Static SQL query
Static SQL query:
static SQL query may or may not have condition and it it has condition
then condition value have to be hard coded in SQL query.
i.e.

1. SELECT* FROM student_detail
2. SELECT* FROM student_detail where user_id=2;
3. INSERT INTO student_detail VALUES(4,'milan','Khanpara');
JDBC program which fetch data from database using 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
97
98
99
100
101
102
103
104
105
106
package com.spy.javaforlearn;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
import com.mysql.jdbc.Driver;
 
public class Myfirstjdbcprog 
{
 
	public static void main(String[] args)
	{
 
		Connection con=null;
		Statement stmt=null;
		ResultSet rs=null;
 
 
		try
		{
 
			/*
			 * load the driver
			 */
			 Driver rf1 = new Driver();
		         DriverManager.registerDriver(rf1);
 
           /*
	    * get the db connection via driver
            * 
            */
 
	 String url="jdbc:mysql://localhost:3306/test?user=root&password=root";
	 con=DriverManager.getConnection(url);
 
		/*
		 * 
		 * issues sql query via connection
		 * 
		 */
 
		//Static SQL query
		String query="select *from student_detail where user_id=1";
		stmt=con.createStatement();
		rs=stmt.executeQuery(query);
 
		/*
		 * process the result return by sql 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(SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
			if(con!=null)
			{
				con.close();
			}
			if(stmt!=null)
			{
				stmt.close();
			}
 
			if(rs!=null)
			{
				rs.close();
			}	
		    }
 
			catch(SQLException e)
 
			 {
				e.printStackTrace();
			 }
 
 
			}
 
		}
 
	}
 
output:
user_id:1
first name:bhavesh
last name:lakhani