首页  >  文章  >  数据库  >  java连接mysql数据库_MySQL

java连接mysql数据库_MySQL

WBOY
WBOY原创
2016-06-01 13:31:47798浏览

bitsCN.com

在此与大家分享一个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();
  }
 }
}

bitsCN.com
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn