forked from mthli/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestDB.java
More file actions
70 lines (62 loc) · 1.93 KB
/
TestDB.java
File metadata and controls
70 lines (62 loc) · 1.93 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
package test;
import java.nio.file.*;
import java.sql.*;
import java.io.*;
import java.util.*;
/**
* This program tests that the database and the JDBC driver are correctly configured.
* @version 1.02 2012-06-05
* @author Cay Horstmann
*/
public class TestDB
{
public static void main(String args[]) throws IOException
{
try
{
runTest();
}
catch (SQLException ex)
{
for (Throwable t : ex)
t.printStackTrace();
}
}
/**
* Runs a test by creating a table, adding a value, showing the table contents, and removing the
* table.
*/
public static void runTest() throws SQLException, IOException
{
try (Connection conn = getConnection())
{
Statement stat = conn.createStatement();
stat.executeUpdate("CREATE TABLE Greetings (Message CHAR(20))");
stat.executeUpdate("INSERT INTO Greetings VALUES ('Hello, World!')");
try (ResultSet result = stat.executeQuery("SELECT * FROM Greetings"))
{
if (result.next())
System.out.println(result.getString(1));
}
stat.executeUpdate("DROP TABLE Greetings");
}
}
/**
* Gets a connection from the properties specified in the file database.properties.
* @return the database connection
*/
public static Connection getConnection() throws SQLException, IOException
{
Properties props = new Properties();
try (InputStream in = Files.newInputStream(Paths.get("database.properties")))
{
props.load(in);
}
String drivers = props.getProperty("jdbc.drivers");
if (drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username, password);
}
}