节制器组件JDBC数据库操纵的JAVABEAN
在节制器组件中,我们最常常做的是与数据库举办交互。这里,我们写一个javabean,用于封装与数据库的操纵,主要是毗连数据库,插入修改删除等更新操纵和查询操纵。代码很简朴如下(需完善):
Java代码
package com.newland.nlie.highway.pub_com;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.sql.DataSource;
public class DatabaseBean extends java.lang.Object {
private Connection conn = null;
private Statement stmt = null;
/**
* 结构函数
*/
public DatabaseBean() {
}
/**
* 通过JNDI成立毗连
*/
private void build_conn() throws Exception {
try {
Context ctx = init_bean.get_init_ctx();
// forJBoss
Object obj = ctx.lookup("java:OracleDS");
// forWebSphere
// Object obj = ctx.lookup("Pub_DataSource");
DataSource ds = (DataSource) obj;
this.conn = ds.getConnection();
this.stmt = conn.createStatement();
} catch (Exception ex) {
}
}
/**
* 获取PreparedStatement工具
*/
public PreparedStatement get_statment(String sql)
throws java.lang.Exception {
try {
if (conn == null)
build_conn();
PreparedStatement preparedStatement = conn.prepareStatement(sql);
return preparedStatement;
} catch (Exception ex) {
throw ex;
}
}
/**
* 执行更新操纵
*/
public void execute_update(String sql) throws Exception {
try {
if (conn == null)
build_conn();
stmt.executeUpdate(sql);
} catch (Exception ex) {
}
}
/**
* 执行查询操纵
*/
public ResultSet execute_query(String sql) throws Exception {
ResultSet rs = null;
try {
if (this.conn == null)
build_conn();
rs = stmt.executeQuery(sql);
} catch (Exception ex) {
}
return rs;
}
/**
* 配置是否自动提交
*/
public void set_auto_commnit(boolean ac) {
try {
if (this.conn == null)
build_conn();
conn.setAutoCommit(ac);
} catch (Exception ex) {
}
}
/**
* 回滚
*/
public boolean rollback() {
try {
if ((conn != null) && (!conn.getAutoCommit())) {
conn.rollback();
}
return true;
} catch (SQLException ex) {
return false;
}
}
/**
* 封锁数据库
*
*/
public void close() {
try {
if (stmt != null)
stmt.close();
if (conn != null) {
if (!conn.isClosed()) {
conn.close();
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
完成后,在节制器组件里可以通过DatabaseBean的execute_update()要领来执行更新操纵,通过execute_query()来执行查询操纵。这里执行的查询操纵后把功效集放在ParamBean里(关于parambean的内容请参看前一篇的文章《如安在节制器组件与模子组件彼此传送数据》)。至此,完成了这个DatabaseBean的说明:)