-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect_query.java
More file actions
124 lines (95 loc) · 2.83 KB
/
select_query.java
File metadata and controls
124 lines (95 loc) · 2.83 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Project2;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.sun.rowset.CachedRowSetImpl;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author DEBOSHREE BANERJEE
*/
public class select_query
{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/db";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
static String arr[]= new String[4];
public static CachedRowSetImpl createConnection(int card_n)
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
CachedRowSetImpl crs = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
JOptionPane.showMessageDialog(null, "Connecting to a selected database...");
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
JOptionPane.showMessageDialog(null, "Connected database successfully...");
//STEP 4: Execute a query
int flag=0;
try
{
//String sql = "insert into registration (card_number,name,h_f_name,department,designation) values (?,?,?,?,?)";
stmt = (PreparedStatement) conn.prepareStatement("SELECT * FROM registration WHERE card_number = ? ");
stmt.setObject(1,card_n);
rs=(ResultSet) stmt.executeQuery();
crs = new CachedRowSetImpl();
crs.populate(rs);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"No such record. ");
flag=1;
}
//stmt.executeUpdate(sql);
if(flag==0)
{
JOptionPane.showMessageDialog(null,"Fetched record from table!..");
}
}
catch(SQLException se)
{
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e)
{
//Handle errors for Class.forName
JOptionPane.showMessageDialog(null,"ERROR!");
e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
}// do nothing
try
{
if(conn!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
}//end try
JOptionPane.showMessageDialog(null,"Goodbye!");
return crs;
}//end main
}