-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJDBCSQLStatement.java
More file actions
70 lines (54 loc) · 1.95 KB
/
JDBCSQLStatement.java
File metadata and controls
70 lines (54 loc) · 1.95 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
package jdbcconnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCSQLStatement {
private static String URL = "jdbc:mysql://localhost:3306/hr";
private static String DbUserName = "root";
private static String DbPassword = "password";
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(URL, DbUserName, DbPassword);
System.out.println("Connected to MySql database...");
statement = connection.createStatement();
resultSet = statement.executeQuery("Select * from countries");
while (resultSet.next()) {
System.out
.println(resultSet.getString("country_name") + "'s ID is " + resultSet.getString("country_id"));
}
System.out.println("#################QUERY 2 ON THE WAY ############");
resultSet.previous();
resultSet.previous();
System.out
.println(resultSet.getString("country_name") + "'s ID is " + resultSet.getString("country_id"));
resultSet.close();
resultSet=statement.executeQuery("SELECT last_name, department_name"
+ " FROM employees e join departments d"
+ " ON e.department_id=d.department_id");
while(resultSet.next()){
System.out.println(resultSet.getString("last_name") +" works in "+resultSet.getString("department_name")+
" Department.");
}
} catch (SQLException e) {
System.out.println("Something went wrong!");
e.printStackTrace();
} finally { // finally block always runs, and below conditions make sure
// that we are not trying to close,
// Not opened connections
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
}