1
+ //STEP 1. Import required packages
2
+ import java .sql .*;
3
+
4
+ public class Exp10_2 {
5
+ // JDBC driver name and database URL
6
+ static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver" ;
7
+ static final String DB_URL = "jdbc:mysql://localhost/emp?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC" ;
8
+ static final String USER = "root" ;
9
+ static final String PASS = "" ;
10
+
11
+ public static void main (String [] args ) {
12
+ Connection conn = null ;
13
+ Statement stmt = null ;
14
+ try {
15
+ //STEP 2: Register JDBC driver
16
+ Class .forName ("com.mysql.cj.jdbc.Driver" );
17
+
18
+ //STEP 3: Open a connection
19
+ System .out .println ("Connecting to database..." );
20
+ conn = DriverManager .getConnection (DB_URL ,USER ,PASS );
21
+
22
+ //STEP 4: Execute a query
23
+ System .out .println ("Creating statement..." );
24
+ stmt = conn .createStatement ();
25
+ String sql ;
26
+ sql = "SELECT id, first, last, age FROM registration" ;
27
+ ResultSet rs = stmt .executeQuery (sql );
28
+
29
+ //STEP 5: Extract data from result set
30
+ while (rs .next ()){
31
+ //Retrieve by column name
32
+ int id = rs .getInt ("id" );
33
+ int age = rs .getInt ("age" );
34
+ String first = rs .getString ("first" );
35
+ String last = rs .getString ("last" );
36
+
37
+ //Display values
38
+ System .out .print ("ID: " + id );
39
+ System .out .print (", Age: " + age );
40
+ System .out .print (", First: " + first );
41
+ System .out .println (", Last: " + last );
42
+ }
43
+ //STEP 6: Clean-up environment
44
+ rs .close ();
45
+ stmt .close ();
46
+ conn .close ();
47
+ }catch (SQLException se ){
48
+ //Handle errors for JDBC
49
+ se .printStackTrace ();
50
+ }catch (Exception e ){
51
+ //Handle errors for Class.forName
52
+ e .printStackTrace ();
53
+ }finally {
54
+ //finally block used to close resources
55
+ try {
56
+ if (stmt !=null )
57
+ stmt .close ();
58
+ }catch (SQLException se2 ){
59
+ }// nothing we can do
60
+ try {
61
+ if (conn !=null )
62
+ conn .close ();
63
+ }catch (SQLException se ){
64
+ se .printStackTrace ();
65
+ }//end finally try
66
+ }//end try
67
+ System .out .println ("Goodbye!" );
68
+ }//end main
69
+ }//end FirstExample
0 commit comments