首頁  >  文章  >  資料庫  >  java连接mysql数据库_MySQL

java连接mysql数据库_MySQL

WBOY
WBOY原創
2016-06-01 13:31:47835瀏覽

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