控制器组件JDBC数据库操作的JAVABEAN
2009-09-06 00:00:00 来源:WEB开发网在控制器组件中,我们最经常做的是与数据库进行交互。这里,我们写一个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();
}
}
}
赞助商链接