java连接mysql数据库

java连接mysql数据库的封装类

public class DB {
 
 static {
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
 
 private DB() {}
 
 public static Connection getConn() {
  Connection conn = null; 
  try{
   conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase?" + "user=root&password=root");
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return conn;
 }
 
 public static void closeConn(Connection conn) {
  try {
   if(conn != null) {
    conn.close();
    conn = null;
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
 
 public static Statement getStmt(Connection conn){
  Statement stmt = null;
  try {
   stmt = conn.createStatement();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return stmt;
 }
 
 public static void closeStmt(Statement stmt) {
  try {
   if(stmt != null) {
    stmt.close();
    stmt = null;
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
 //根据conn,sql得到pStmt
 public static PreparedStatement getPStmt(Connection conn, String sql){
  PreparedStatement pStmt = null;
  try {
   pStmt = conn.prepareStatement(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return pStmt;
 }
 //根据stmt,sql得到结果集
 public static ResultSet executeQuery(Statement stmt, String sql){
  ResultSet rs = null;
  try {
   rs = stmt.executeQuery(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return rs;
 }

//根据conn,sql得到结果集
 public static ResultSet executeQuery(Connection conn, String sql){
  ResultSet rs = null;
  try {
   rs = conn.createStatement().executeQuery(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return rs;
 }
 
 public static void closeResultSet(ResultSet rs) {
  try {
   if(rs != null) {
    rs.close();
    rs = null;
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
}

posted on 2013-07-22 12:50  凯特的宝贝世界  阅读(291)  评论(0编辑  收藏  举报