Heim  >  Artikel  >  Datenbank  >  java连接mysql数据库_MySQL

java连接mysql数据库_MySQL

WBOY
WBOYOriginal
2016-06-01 13:31:47798Durchsuche

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
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn