-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.java
More file actions
78 lines (71 loc) · 2.21 KB
/
Copy pathApp.java
File metadata and controls
78 lines (71 loc) · 2.21 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
71
72
73
74
75
76
77
78
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
public class App {
final String databaseURL = "jdbc:postgresql://localhost/";
final static String user = "postgres";
final static String password = "";
Connection connection;
PreparedStatement preparedStatement;
ResultSet rs;
Statement statement;
public App() throws Exception{
Class.forName("org.postgresql.Driver");
try {
connection = DriverManager.getConnection(databaseURL, user, password);
statement = connection.createStatement();
statement.execute("DROP TABLE IF EXISTS test;");
statement.execute("CREATE TABLE test (city varchar(20), state char(2));");
} catch (java.sql.SQLException ex) {
System.out.println("Failed to set up database.");
}
}
public void insertData() {
try {
connection = DriverManager.getConnection(databaseURL, user, password);
preparedStatement = connection.prepareStatement("INSERT INTO test (city, state) VALUES (?, ?);");
preparedStatement.setString(1, "Seattle");
preparedStatement.setString(2, "WA");
preparedStatement.executeUpdate();
} catch (java.sql.SQLException ex) {
} finally {
try {
preparedStatement.close();
} catch (java.sql.SQLException ex) {
preparedStatement = null;
}
try {
connection.close();
} catch (java.sql.SQLException ex) {
connection = null;
}
}
}
public String getData() {
String toReturn = "";
try {
connection = DriverManager.getConnection(databaseURL, user, password);
preparedStatement = connection.prepareStatement("SELECT * FROM test");
rs = preparedStatement.executeQuery();
if (rs.next()) {
toReturn = rs.getString("city") + ", " + rs.getString("state");
}
} catch (java.sql.SQLException ex) {
} finally {
try {
preparedStatement.close();
} catch (java.sql.SQLException ex) {
preparedStatement = null;
}
try {
connection.close();
} catch (java.sql.SQLException ex) {
connection = null;
}
return toReturn;
}
}
}