//TestDB.java
package lGX;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.io.*;
public class TestDB {
public static void main(String[] args) {
try {
runTest();
} catch (SQLException ex) {
for (Throwable t : ex) {
t.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void runTest() throws IOException, SQLException {
Connection conn = getConnection();
try {
Statement stat = conn.createStatement();
stat.executeUpdate("create table Greetings (Message CHAR(20))");
stat.executeUpdate("insert into Greetings values('Hello,Word!')");
ResultSet result = stat.executeQuery("select * from Greetings");
if (result.next()) {
System.out.println(result.getString(1));
result.close();
stat.execute("drop table Greetings");
}
} finally {
conn.close();
}
}
public static Connection getConnection() throws SQLException, IOException {
Properties props = new Properties();
FileInputStream in = new FileInputStream("databaseConf.properties");
props.load(in);
in.close();
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);
}
}
//databaseConf.properties
jdbc.drivers=com.mysql.jdbc
jdbc.url=jdbc:mysql://localhost/corejava
jdbc.username=dbuser
jdbc.password=secretMySQL
驱动下载:http://mysql.stu.edu.tw/Downloads/Connector-J/mysql-connector-java-5.1.18.tar.gz
MySQL数据库下载:http://mirrors.sohu.com/mysql/