· 6 years ago · Jul 31, 2019, 12:18 AM
1package MySQL;
2import java.sql.*;
3import java.sql.DriverManager;
4
5public class WorkMySQL
6{
7 // JDBC driver name and database URL
8 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
9 static final String DB_URL = "jdbc:mysql://localhost/employeesDataBase";
10 // Database credentials
11 static final String USER = "root";
12 static final String PASS = "Khro18032001";
13
14 public static void main(String[] args)
15 {
16 Connection conn = null;
17 Statement stmt = null;
18
19 try
20 {
21 //STEP 2: Register JDBC driver
22 Class.forName("com.mysql.cj.jdbc.Driver");
23
24 //STEP 3: Open a connection
25 System.out.println("Connecting to database...");
26 conn = DriverManager.getConnection(DB_URL + "?useTimezone=true&serverTimezone=UTC", USER, PASS);
27
28 //STEP 4: Execute a query
29 System.out.println("Creating table in given database...");
30 stmt = conn.createStatement();
31 String sql = "CREATE TABLE IF NOT EXISTS Employees0" +
32 "(id INTEGER not NULL, " +
33 " first VARCHAR(255), " +
34 " last VARCHAR(255), " +
35 " age INTEGER, " +
36 " PRIMARY KEY ( id ))";
37 stmt.executeUpdate(sql);
38 System.out.println("Created table in given database...");
39
40 System.out.println("Inserting records into the table...");
41 sql ="INSERT INTO Employees0 VALUES (100, 'Kriss', 'Kurian', 18)";
42 stmt.executeUpdate(sql);
43 sql = "INSERT INTO Employees0 VALUES (101, 'Enrique', 'John', 25)";
44 stmt.executeUpdate(sql);
45 sql= "INSERT INTO Employees0 VALUES (102, 'Taylor', 'Swift', 30)";
46 stmt.executeUpdate(sql);
47 sql= "INSERT INTO Employees0 VALUES(103, 'Linkin', 'Park', 28)";
48 stmt.executeUpdate(sql);
49 System.out.println("Inserted records into the table...");
50
51 System.out.println("Creating statement...");
52 sql = "SELECT id, first, last, age FROM Employees0";
53 ResultSet rs = stmt.executeQuery(sql);
54
55 //STEP 5: Extract data from result set
56 while(rs.next())
57 {
58 //Retrieve by column name
59 int id = rs.getInt("id");
60 int age = rs.getInt("age");
61 String first = rs.getString("first");
62 String last = rs.getString("last");
63 //Display values
64 System.out.print("ID: " + id);
65 System.out.print(", Age: " + age);
66 System.out.print(", First: " + first);
67 System.out.println(", Last: " + last);
68 }
69
70 //STEP 6: Clean-up environment
71 rs.close();
72 stmt.close();
73 conn.close();
74
75 }
76
77 catch(SQLException se)
78 {
79 //Handle errors for JDBC
80 se.printStackTrace();
81 }
82 catch(Exception e)
83 {
84 //Handle errors for Class.forName
85 e.printStackTrace();
86 }
87 finally
88 {
89 //finally block used to close resources
90 try
91 {
92 if(stmt!=null)
93 stmt.close();
94 }
95 catch(SQLException se2)
96 {
97 }// nothing can be done
98 try
99 {
100 if(conn!=null)
101 conn.close();
102 }
103 catch(SQLException se)
104 {
105 se.printStackTrace();
106 }//end finally try
107 }//end finally
108 System.out.println("Goodbye!");
109 }//end main
110} // end Class