⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dao.java

📁 数学网
💻 JAVA
字号:
package math.dao;

import java.sql.*;

import javax.sql.*;


public class DAO {

  protected DataSource ds;

  public int getSize(String tableName, String condition) throws SQLException {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      String sql = "SELECT count(*) FROM " + tableName + " " + condition;
      conn = ds.getConnection();
      pstmt = conn.prepareStatement(sql);
      rs = pstmt.executeQuery();
      rs.next();
      int size = rs.getInt(1);
      close(rs);
      close(pstmt);
      return size;
    }
    catch (SQLException sqle) {
      close(rs);
      close(pstmt);
      rollback(conn);
      sqle.printStackTrace();
      throw sqle;
    }
    finally {
      close(conn);
    }
  }

  public DAO(DataSource ds) {
    this.ds = ds;
  }

  public void setDataSource(DataSource ds) {
    this.ds = ds;
  }

  protected void close(ResultSet rs) {
    if (rs != null) {
      try {
	rs.close();
      }
      catch (SQLException e) {
      }
      rs = null;
    }
  }

  protected void close(PreparedStatement pstmt) {
    if (pstmt != null) {
      try {
	pstmt.close();
      }
      catch (SQLException e) {
      }
      pstmt = null;
    }
  }

  protected void close(Connection conn) {
    if (conn != null) {
      try {
	conn.close();
      }
      catch (SQLException e) {
	e.printStackTrace();
      }
      conn = null;
    }
  }

  protected void rollback(Connection conn) {
    if (conn != null) {
      try {
	conn.rollback();
      }
      catch (SQLException e) {
	e.printStackTrace();
      }
      conn = null;
    }
  }

  protected static String java2sqlName(String name) {
    String column = "";
    for (int i = 0; i < name.length(); i++) {
      if (i < name.length() - 1 &&
	  (name.charAt(i) >= 'a' && name.charAt(i) <= 'z') &&
	  (name.charAt(i + 1) >= 'A' && name.charAt(i + 1) <= 'Z')) {
	column += name.charAt(i) + "_";
      }
      else {
	column += name.charAt(i);
      }
    }
    return column.toLowerCase();
  }

  protected static String sql2javaName(String name) {
    String column = "";
    for (int i = 0; i < name.length(); i++) {
      if (name.charAt(i) == '_') {
	column += ++i < name.length() ?
	    String.valueOf(name.charAt(i)).toUpperCase() : "";
      }
      else {
	column += name.charAt(i);
      }
    }
    return column;
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -