forked from Bhagabat/JavaExamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
96 lines (80 loc) · 2.54 KB
/
Main.java
File metadata and controls
96 lines (80 loc) · 2.54 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* Author: Edwin Torres
* email: CoachEd@gmail.com
* Description: This program shows how to connect to a
* PostgreSQL database from Java.
*
*/
public class Main {
private Connection conn = null;
public static void main(String[] args) {
Main obj = new Main();
/* PostgreSQL server details (CHANGE THESE VALUES) */
String server = "127.0.0.1";
String database = "dbName";
String username = "user1";
String password = "pass1";
/** create the url string for the connection */
String url = "jdbc:postgresql://" + server + "/" + database;
/** establish the connection */
try {
/** register the database driver */
Class.forName("org.postgresql.Driver");
/** get the connection */
obj.setConn(DriverManager.getConnection(url, username, password));
} catch (ClassNotFoundException e) {
obj.setConn(null);
e.printStackTrace();
} catch (SQLException e) {
obj.setConn(null);
e.printStackTrace();
} catch (Exception e) {
obj.setConn(null);
e.printStackTrace();
}
/** use the connection */
if (obj.getConn() != null) {
obj.queryDatabase();
}
/** close the connection */
try {
if (obj.getConn() != null) {
obj.getConn().close();
obj.setConn(null);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queryDatabase() {
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM yourTable"; //CHANGE THIS
rs = stmt.executeQuery(sql);
while(rs.next()){
//display first column
System.out.println(rs.getString(1));
}
rs.close();
stmt.close();
} catch (SQLException e) {
stmt = null;
rs = null;
e.printStackTrace();
}
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
}