-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbConnectionUtil.java
85 lines (74 loc) · 2.51 KB
/
DbConnectionUtil.java
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
package DataBaseConnection.mySqlDb.FetchDataFromDb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbConnectionUtil {
private static String dbUrl;
private static Connection dbConnection;
/**
* method to form a connection URL and send it to establshSqlDbConnection method.
* @param hostname hostname
* @param dbUserName dbUserName
* @param dbPassword dbPassword
* @param dbName dbName
* @param port port
*/
public DbConnectionUtil(String hostname, String port, String dbName, String dbUserName, String dbPassword){
dbUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword;
System.out.println("dbUrl:"+dbUrl);
if(dbConnection==null)
dbConnection = establshSqlDbConnection();
}
/**
* method to establish the SQL db connection
* @return Connection
*/
public static Connection establshSqlDbConnection(){
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection dbConnection = DriverManager.getConnection(dbUrl);
System.out.println("Db Connection is successful - "+dbUrl);
return dbConnection;
} catch (ClassNotFoundException | SQLException ex ) {
System.out.println("Error while connecting to Database " + ex.getMessage());
}
return dbConnection ;
}
public Connection getDbConnection(){
return dbConnection;
}
public String getDbUrl() {
return dbUrl;
}
/**
* method to close the dbConnection
*/
public static void closeDbConnection(){
if(dbConnection != null){
try {
dbConnection.close();
System.out.println("DB connection closed");
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
}
/**
* method to return ResultSet after query execution
* @param query sql-query
* @return ResultSet
*/
public static ResultSet executeQuery(String query) {
Statement statement = null;
ResultSet queryResultSet = null;
try {
statement = dbConnection.createStatement();
queryResultSet = statement.executeQuery(query);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return queryResultSet;
}
}