forked from CodeTheChangeUBC/buddyapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadDatabaseTest.java
83 lines (71 loc) · 2.8 KB
/
ReadDatabaseTest.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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class ReadDatabaseTest {
public static void main(String[] args) throws Exception {
// Initialize connection variables.
String host = "moonwalk-1.postgres.database.azure.com";
String database = "postgres";
String user = "moonwalk@moonwalk-1";
String password = "";//add password
// check that the driver is installed
try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}
System.out.println("PostgreSQL JDBC driver detected in library path.");
Connection connection = null;
// Initialize connection object
try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);
// set up the connection properties
Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");
// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");
// Perform some SQL queries over the connection.
try
{
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * from inventory;");
//Replace 'inventory' with any table such as 'public.user'
while (results.next())
{
String outputString =
String.format(
"Data row = (%s, %s, %s)",
results.getString(1),
results.getString(2),
results.getString(3));
System.out.println(outputString);
}
}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}