mysql数据库的封装

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Dao {
 protected static Connection cnt = null;
 protected static Statement stmt;
 protected static ResultSet rs;
 protected static String dbClassName = "org.gjt.mm.mysql.Driver";
 /*
  * 连接数据库
  */
 protected Dao() {
  if (cnt == null) {
   try {
    Class.forName(dbClassName);
    cnt = DriverManager
      .getConnection("jdbc:mysql://localhost/dataname?"
        + "user=users&password=key");
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   } catch (SQLException s) {
    System.out.print("出错");
    s.printStackTrace();
   }
  } else
   return;
 }
 /*
  * 查询语句
  */
 public static ResultSet executeQuery(String sql) {
  try {
   if (cnt == null)
    new Dao();
   return (cnt.createStatement().executeQuery(sql));
  } catch (SQLException e) {
   e.printStackTrace();
   return null;
  } finally {
  }
 }
 /*
  * 更新(添加)语句
  */
 public static int executeUpdate(String sql) {
  try {
   if (cnt == null)
    new Dao();
   return cnt.createStatement().executeUpdate(sql);
  } catch (SQLException e) {
   e.printStackTrace();
   return -1;
  } finally {
  }
 }
 /*
  * 断开数据库连接,关闭文件
  */
 public static void CloseAll() {
  try {
   if (rs != null) {
    rs.close();
    rs = null;
   }
   if (stmt != null) {
    stmt.close();
    stmt = null;
   }
   if (cnt != null) {
    cnt.close();
    cnt = null;
   }
  } catch (SQLException ac) {
   ac.printStackTrace();
  }
 }
}

你可能感兴趣的:(mysql,数据库封装)