您的位置:首页 > 编程语言 > Java开发

JavaWeb之BaseDao的写法

2016-06-18 13:28 405 查看
package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* 用来做数据的基础连接和相关操作的关闭
* @author Lulu
*
*/
public class BaseDAO {
public BaseDAO() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

// 属性 --------------------------
private Connection conn;
private Statement stm;
private PreparedStatement pstm;
private ResultSet rs;

// 获得连接--------------------------
public Connection getConn() {
try {
if (conn == null || conn.isClosed()) {

conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bbs",
"root", "");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("getConnection()错误");
}
return conn;
}

// 执行增、删、改SQL语句--------------------
/**
*
* @param sql
* @return int表示影响的行数
* @throws SQLException
*/
public int executeUpdate(String sql) throws SQLException {
if (getConn() == null) {
System.out.println("与数据库连接失败!");
return -1;
}
stm = conn.createStatement();
return stm.executeUpdate(sql);
}

// 重载执行增、删、改SQL语句--------------------
public int executeUpdate(String sql, Object[] obj) throws SQLException {

if (getConn() == null) {
System.out.println("与数据库连接失败!");
return -1;
}
pstm = conn.prepareStatement(sql);
if (obj != null) {
for (int i = 0; i < obj.length; i++) {
pstm.setObject(i + 1, obj[i]);
}
}
return pstm.executeUpdate();
}

// 执行查询SQL语句----------------------------
public ResultSet executeQuery(String sql) throws SQLException {
if (getConn() == null) {
System.out.println("与数据库连接失败!");
return null;
}
stm = conn.createStatement();
rs = stm.executeQuery(sql);
return rs;
}

// 重载执行查询SQL语句----------------------------
public ResultSet executeQuery(String sql, Object[] obj) throws SQLException {
//第一步获取链接
if (getConn() == null) {//该步骤完成了与数据库的链接操作
System.out.println("与数据库连接失败!");
return null;
}
//将数据准备一下
pstm = conn.prepareStatement(sql);
if (obj != null) {
for (int i = 0; i < obj.length; i++) {
pstm.setObject(i + 1, obj[i]);
}
}
//执行完整sql语句
rs = pstm.executeQuery();
return rs;
}

// 关闭ResultSet
public void closeResultSet() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

// 关闭Connection
public void closeConnection() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

// 关闭Statement和PreparedStatement
public void closeStatement() {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java web