Home  >  Article  >  Database  >  java连接mysql数据库_MySQL

java连接mysql数据库_MySQL

WBOY
WBOYOriginal
2016-06-01 13:31:47833browse

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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn