用java实现数据库应用系统(1)
我们在做信息系统的时候,都要访问数据库,我最近接手一个项目,项目组决定使用java编写,我负责数据层的设计和编码,为了提高代码的重用性和提高项目的开发效率。我们开发了一个通用的数据库连接和完成基本操作的类库,个人认为这个类在做mis系统时还是有一定的价值,所以总结出来,介绍给大家。
连接工厂,实现了datasource接口
package skydev.modules.data;
import java.sql.*;
import javax.sql.datasource;
import java.io.printwriter;
public class connectionfactory implements datasource {
private string username;
private string password;
private string drivername;
private string url;
private java.sql.connection connection;
/**
* 根据设置的连接参数创建一个新的连接实例
* @return
*/
private connection getnewconnection() {
try {
this.connection.close(); //试图关闭连接
}
finally {
this.connection = null; //释放连接
try {
class.forname(this.drivername); //加载驱动程序
//drivermanager.registerdriver(driver);
try {
this.connection = drivermanager.getconnection(this.url, this.username,
this.password);
}
catch (sqlexception e) {
throw e;
}
}
finally {
return this.connection; //返回新建立的连接
}
}
}
public string getusername() {
return username;
}
public void setusername(string username) {
this.username = username;
}
public string getpassword() {
return password;
}
public void setpassword(string password) {
this.password = password;
}
public string getdrivername() {
return drivername;
}
public void setdrivername(string drivername) {
this.drivername = drivername;
}
public string geturl() {
return url;
}
public void seturl(string url) {
this.url = url;
}
public java.sql.connection getconnection() {
if (connection != null) {
try {
if (connection.isclosed()) {
connection = null;
getnewconnection();
}
}
catch (sqlexception ex) {
}
}
if (connection == null) { //没有设置连接则创建一个连接
getnewconnection();
}
return connection;
}
public connection getconnection(string username, string password) throws
sqlexception {
this.setusername(username);
this.setpassword(password);
return getconnection();
}
public printwriter getlogwriter() {
return null;
}
public void setlogwriter(printwriter printwriter) {
}
public void setlogintimeout(int int0) {
}
public int getlogintimeout() {
return 0;
}
}
(未完待续)
闽公网安备 35060202000074号