首先
把资源文件(*.properties)放到classes目录下:
例如:
dataresources.properties
driver=sun.jdbc.odbc.JdbcOdbcDriver
uri=jdbc:odbc:(数据源名称)
userName=sa
passWord=
接下来申明一个类来获取加载资源文件:
import java.util.Properties;
import java.io.InputStream;
import java.io.*;
public class InitResource
{
static String driver;
static String uri;
static String username;
static String password;
public InitResource() {}
static{
InputStream in=null;
/** * 通过如下代码来测试路径 * URL u = InitResource.class.getResource("/"); *将properties文件放到classes根目录下 * */
try{
in=InitResource.class.getResourceAsStream ("/datasource.properties");
Properties p=new Properties();
p.load(in);
driver=p.getProperty("driver");
uri=p.getProperty("uri");
username=p.getProperty("userName");
password=p.getProperty("passWord");
} catch (IOException ex) { ex.printStackTrace(); }
}
}
接下来写正常的连接了:
import java.sql.*;
public class BaseDao{
private Connection con;
private Statement stmt;
private ResultSet rs;
static{
try{
Class.forName(InitResource.driver);
}catch(ClassNotFoundException ex){
ex.printStackTrace();
}
}
public BaseDao(){
this.openConnection();
}
public voide openConnection(){
try{
con=DriverManager.getConnection(InitResource.url,InitResouce.
username,InitResource.password);
}catch(SqlException e){
System.out.println("getConnection()内的错误跟踪:" + e.getMessage());
}
}
public boolean closeConne() {
try {
if(rs!=null) {
rs.close();
rs =null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null && con.isClosed()) {
con.close();
con = null; }
} catch (SQLException ox) {
System.out.println(ox);
return false;
}
return true;
}
public int executeUpdate(String sql) {
try {
stmt = con.createStatement();
return stmt.executeUpdate(sql);
} catch (SQLException ex) {
ex.printStackTrace();
return -1;
}
}
public ResultSet executeQuery(String sql) {
try { stmt = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
return stmt.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
}