forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDerbyDataSourceEx.java
More file actions
68 lines (49 loc) · 1.65 KB
/
DerbyDataSourceEx.java
File metadata and controls
68 lines (49 loc) · 1.65 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
package com.zetcode;
import com.zetcode.utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.apache.derby.jdbc.ClientDataSource;
public class DerbyDataSourceEx {
public static void main(String[] args) throws SQLException {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
DataSource ds = getDS("testdb", "app", "app");
con = ds.getConnection();
pst = con.prepareStatement("SELECT * FROM Cars");
rs = pst.executeQuery();
while (rs.next()) {
System.out.print(rs.getInt(1));
System.out.print(": ");
System.out.println(rs.getString(2));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DerbyDataSourceEx.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
DBUtils.closeResultSet(rs);
DBUtils.closeStatement(pst);
DBUtils.closeConnection(con);
}
}
public static DataSource getDS(String database, String user,
String password) {
ClientDataSource ds = new ClientDataSource();
ds.setDatabaseName(database);
if (user != null) {
ds.setUser(user);
}
if (password != null) {
ds.setPassword(password);
}
ds.setServerName("localhost");
ds.setPortNumber(1527);
return ds;
}
}