欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于封装jdbc2 JavaSQLMicrosoftJDBC 

程序员文章站 2022-03-06 13:00:09
...

DBConnectionFactory.java它有一个辅助类DBConnectionConfig.java用来读取配置文件
[code]

public class DBConnectionConfig {

private static Properties prop = new Properties();

static {

try {
prop.load(DBConnectionConfig.class
.getResourceAsStream("DBConnectionConfig.properties"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static String className = prop.getProperty("className");

}

[/code]

接下来才是我怎么去访问数据库了,这里我写了一个接口

具体是谁是获得连接对象,让实现该接口的类去做吧


[code]

package org.cdy.www.service;

import java.sql.Connection;

public interface IDBConnection {

public abstract Connection getConnection();

public abstract void closeConnection(Connection conn);
}

[/code]

由于数据库的关闭操作对于所有实现该接口的类都是采用一样的方法conn.close()所有我写了一个抽象类AbstractConnectionImpl.java


[code]

import java.sql.Connection;
import java.sql.SQLException;

import org.cdy.www.service.IDBConnection;

public abstract class AbstractConnectionImpl implements IDBConnection {

public void closeConnection(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public Connection getConnection() {
// TODO Auto-generated method stub
return null;
}

}

至于获得连接对象Connection则由各种数据库类自己去实现,它们只需要override就行了

下面是采用MSSQL数据库的方式

package org.cdy.www.serviceImpl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MSSqlConnectionImpl extends AbstractConnectionImpl {

@Override
public Connection getConnection() {
// TODO Auto-generated method stub
Connection conn = null;
try {
Class.forName(MSSqlConnectionConfig.driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(MSSqlConnectionConfig.url,
MSSqlConnectionConfig.user, MSSqlConnectionConfig.password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

@Override
public void closeConnection(Connection conn) {
// T

super.closeConnection(conn);
}

}
它对应自己的配置类、配置文件

package org.cdy.www.serviceImpl;

import java.io.IOException;
import java.util.Properties;

public class MSSqlConnectionConfig {

private static Properties prop = new Properties();

static {
try {
prop.load(MSSqlConnectionConfig.class
.getResourceAsStream("MSSqlConnectionConfig.properties"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static String driver = prop.getProperty("driver");

public static String url = prop.getProperty("url");

public static String user = prop.getProperty("user");

public static String password = prop.getProperty("password");
}

配置文件

driver=com.microsoft.JDBC.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://localhsot:1433;databaseName=test
user=sa
password=sa

[/code]