//?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("连接数据库成功!");
}
}
配置文件:
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
serverURL=jdbc:microsoft:sqlserver://HPK\\SQLEXPRESS:1433;databaseName=809
username=sa
password=redphase
sqljdbc_4.0已经导入项目中
但是运行后提示:
java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://HPK\SQLEXPRESS:1433;databaseName=809
怎么处理
sql2005 jdbc 数据库 sqlserver
------解决方案--------------------
多了一个sqljdbc.jar