1. 程式人生 > >Java訪問MySQL資料庫的SqlHelper類

Java訪問MySQL資料庫的SqlHelper類

第一步:新建SqlHelper類;

第二步:新建一個屬性檔案dbinfo.properties,具體內容如下:

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test
userName=root
password=123456


第三步:完成SqlHelper類;一定要記著引入資料庫驅動程式。SqlHelper類的具體內容如下:
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class SqlHelper {
    //定義要使用的變數
    private static Connection conn = null;
    private static PreparedStatement ps = null;
    private static ResultSet rs = null;
    private static CallableStatement cs = null;

    private static String driver = "";
    private static String url = "";
    private static String userName = "";
    private static String password = "";

    private static Properties pp = null;
    private static InputStream fis = null;

    public static Connection getConn() {
       return conn;
    }

    public static PreparedStatement getPs() {
       return ps;
    }

    public static ResultSet getRs() {
       return rs;
    }
   
    public static CallableStatement getCs() {
       return cs;
    }

    //載入驅動,只需要一次
    static{
       try {
          //從配置檔案dbinfo.properties中讀取配置資訊
          pp = new Properties(); 
          SqlHelper.class.getClassLoader().getResourceAsStream("dbinfo.properties");
         pp.load(fis);
          driver =pp.getProperty("driver");
          url =pp.getProperty("url");
          userName =pp.getProperty("userName");
          password =pp.getProperty("password");
         Class.forName(driver);
       } catch(Exception e) {
         e.printStackTrace();
       } finally{
          if (fis !=null)
             try {
               fis.close();
             } catch(IOException e) {
               e.printStackTrace();
             }
          fis =null;

       }
    }

    //得到連線
    public static Connection getConnection() {
       try {
          conn =DriverManager.getConnection(url, userName, password);
       } catch(SQLException e) {
         e.printStackTrace();
       }
       return conn;
    }

    //處理多個update/delete/insert
    public static void executeUpdateMultiParams(String[] sql,
          String[][]parameters) {
       try {
          //獲得連線
          conn =getConnection();
          //可能傳多條sql語句
         conn.setAutoCommit(false);
          for (int i =0; i < sql.length; i++) {
             if(parameters[i] != null) {
                ps =conn.prepareStatement(sql[i]);
                for (int j =0; j < parameters[i].length; j++)
                  ps.setString(j + 1, parameters[i][j]);
             }
            ps.executeUpdate();
          }
         conn.commit();
       } catch(Exception e) {
         e.printStackTrace();
          try {
            conn.rollback();
          } catch(SQLException e1) {
            e1.printStackTrace();
          }
          throw new RuntimeException(e.getMessage());
       } finally{
          //關閉資源
          close(rs,ps, conn);
       }
    }

    //update/delete/insert
    //sql格式:UPDATE tablename SET columnn = ? WHERE column = ?
    public static void executeUpdate(String sql, String[] parameters) {
       try {
          //1.建立一個ps
          conn =getConnection();
          ps =conn.prepareStatement(sql);
          //給?賦值
          if(parameters != null)
             for (int i =0; i < parameters.length; i++) {
               ps.setString(i + 1, parameters[i]);
             }
          // 執行
         ps.executeUpdate();
       } catch(SQLException e) {
         e.printStackTrace();// 開發階段
          throw new RuntimeException(e.getMessage());
       } finally{
          //關閉資源
          close(rs,ps, conn);
       }
    }

    //select
    public static ResultSet executeQuery(String sql, String[] parameters){
       ResultSet rs= null;
       try {
          conn =getConnection();
          ps =conn.prepareStatement(sql);
          if(parameters != null) {
             for (int i =0; i < parameters.length; i++) {
               ps.setString(i + 1, parameters[i]);
             }
          }
          rs =ps.executeQuery();
       } catch(SQLException e) {
         e.printStackTrace();
          throw new RuntimeException(e.getMessage());
       } finally{

       }
       return rs;
    }

    //呼叫無返回值儲存過程
    // 格式: callprocedureName(parameters list)
    public static void callProc(String sql, String[] parameters) {
       try {
          conn =getConnection();
          cs =conn.prepareCall(sql);
          //給?賦值
          if(parameters != null) {
             for (int i =0; i < parameters.length; i++)
               cs.setObject(i + 1, parameters[i]);
          }
         cs.execute();
       } catch(Exception e) {
         e.printStackTrace();
          throw new RuntimeException(e.getMessage());
       } finally{
          //關閉資源
          close(rs,cs, conn);
       }
    }

    //呼叫帶有輸入引數且有返回值的儲存過程
    public static CallableStatement callProcInput(String sql, String[]inparameters) {
       try {
          conn =getConnection();
          cs =conn.prepareCall(sql);
         if(inparameters!=null)
             for(int i=0;i<inparameters.length;i++)
               cs.setObject(i+1,inparameters[i]);            
         cs.execute();
       }
       catch(Exception e) {
         e.printStackTrace();
          throw new RuntimeException(e.getMessage());
      }finally{
         
       }
       return cs;
    }
   
    //呼叫有返回值的儲存過程
    public static CallableStatement callProcOutput(String sql,Integer[]outparameters) {
       try {
          conn =getConnection();
          cs =conn.prepareCall(sql);               
         //給out引數賦值
         if(outparameters!=null)
             for(int i=0;i<outparameters.length;i++)
               cs.registerOutParameter(i+1, outparameters[i]);
         cs.execute();
       }
       catch(Exception e) {
         e.printStackTrace();
          throw new RuntimeException(e.getMessage());
      }finally{
         
       }
       return cs;
    }

    public static void close(ResultSet rs, Statement ps, Connection conn){
       if (rs !=null)
          try {
            rs.close();
          } catch(SQLException e) {
            e.printStackTrace();
          }
       rs =null;
       if (ps !=null)
          try {
            ps.close();
          } catch(SQLException e) {
            e.printStackTrace();
          }
       ps =null;
       if (conn !=null)
          try {
            conn.close();
          } catch(SQLException e) {
            e.printStackTrace();
          }
       conn =null;
    }
}