netbean 用jdbc连sql2005express 问题求救 (sqljdbc_4.0已导入项目)
//?package ch13;
import java.sql.*;
import java.io.*;
import java.util.Properties;
/**
*
* 通过配置connection.txt文件
* 可以获得到各种数据库的连接
*/
public final class DBConnection {
private static String driver;
private static String serverURL;
private static String username;
private static String password;
private static Connection conn = null;
private static String connectionFileName = "src/ch13/connection.txt";
private static Object initLock = new Object();
private DBConnection() { }
public static Connection getConnection() {
if (conn == null) {
synchronized(initLock) {
loadProperties();
try {
Class.forName(driver);
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
try {
conn = DriverManager.getConnection(serverURL, username, password);
}
catch (SQLException e) {
System.out.println(e.toString());
}
}
}
return conn;
}
private static void loadProperties() {
Properties connectionAdmin = new Properties();
System.out.println("连接配置文件:" + connectionFileName);
// 从配置文件中加载参数
try{
connectionAdmin.load(new FileInputStream(connectionFileName));
}
catch(IOException e){
System.out.println("找不到文件:" + connectionFileName);
System.out.println(e.toString());
}
// 设置数据库连接参数
driver = (String)connectionAdmin.get("driver");
serverURL = (String)connectionAdmin.get("serverURL");
username = (String)connectionAdmin.get("username");
password = (String)connectionAdmin.get("password");
}
// Test methods.
public static void main(String[] args) {
System.out.println("开始连接数据库...");
Connection conn = getConnection();
System.out.println("-------------------------------");
System.out.println(" driver: " + driver);
System.out.println("serverURL: " + serverURL);
System.out.println(" username: " + username);
System.out.println(" password: " + password);
System.out.println("-------------------------------");
if (conn != null) System.out.println("连接数据库成功!");
}
}