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);
}
}
1、首先是一个runTest函数,运行一个测试,测试创建一个表格,添加一个值,展示表格内容,然后清除这个表格。
首先是得到getConnection()函数返回的已经建立的Connection。接着使用Connection的createStatement方法创建一个Statement对象,用来向数据库发送SQL指令。
2、这其中首先是一个getConnection()函数,同样的道理,由.properties文件得到一个Path,由Path得到一个InputStream,采用properties的load方法可以从输入流中读取属性列表。
接着从props中读取jdbc.drivers, 然后,将System的jdbc.drivers属性设置为读到的值。然后,读取jdbc.url属性、jdbc.username属性、jdbc.password属性。然后调用DriverManager.getConnection方法,建立到给定url的连接。