カスタムJDBCツールクラス接続MySQLデータベース

4994 ワード

使用するjarパッケージ:mysql-connector-java-5..43-bin.jar
1.データベースに接続するために必要な情報を、propertiesファイルdriver=comであるファイルに保存する.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/javaee1707?useSSL=true user=root password=123456
  • コード実装public class JDBCUtil{private static String url=null;private static String user=null;private static String password=null;private static String driverClass=null;private static InputStream in=null;//静的コードブロックの特徴を利用してクラスファイルをメモリにロードすると、静的コードブロック内のコードstatic{try{//1.読み出しプロファイル情報読み出しpropertiesファイルProperties props=new Properties();
         //    properties        ,     IO 
         in = new FileInputStream("./src/db.properties");
         
         //2.   Properties   load      
         props.load(in);
         
         //3.     Properties   ,        
         url = props.getProperty("url");
         user = props.getProperty("user");
         password = props.getProperty("password");
         driverClass = props.getProperty("driver");
         
         //4.      
         Class.forName(driverClass);
     } catch (IOException | ClassNotFoundException e) {
         // TODO: handle exception
         e.printStackTrace();
         System.out.println("      ");
     } finally {
         //      
         if (in != null) {
             try {
                 in.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
     }
    
    }/**
  • データベース接続オブジェクトの取得
  • @return */public static Connection getConnection() { Connection conn = null; try { conn = DriverManager.getConnection(url, user, password); } catch (SQLException e) {//TODO Auto-generated catch block e.printStackTrace(); } return conn; }

  • /**
  • データベース接続を閉じ、Statement
  • を解放
  • @param connデータベース接続先
  • @param st Statementオブジェクト*/public static void close(Connection conn,Statementst){try{if(st!=null){st.close();}if (conn != null) { conn.close(); } } catch(SQLException e){//TODO:handle exception e.printStackTrace();//糖衣砲弾throw new RuntimeException(e);}//結果セットのあるクエリ文リソースpublic static void close(Connection conn,Statementst,ResultSet){try{if(st!=null){st.close();}を閉じます.if (set != null) { set.close(); } if (conn != null) { conn.close(); } } catch(SQLException e){//TODO:handle exception e.printStackTrace();//糖衣砲弾throw new RuntimeException(e)}}


  • 3.データベースpublic class Demo 2{をカスタムJDBCツールクラスで接続する
    //    
    @Test
    public void createTable() {
        Statement st = null;
    
        //1.         JDBC   ,           
        Connection conn = JDBCUtil.getConnection();
        try {
            //2.   Statement,SQL     , SQL     MySQL  , MySQL  
            st = conn.createStatement();
    
            //3.   SQL  
            String sql = "create table WOW(heroID int not null primary key auto_increment,heroName char(30))";
    
            //4.   Statement  SQL  
            int count = st.executeUpdate(sql);
    
            //5.        
            System.out.println("     :" + count);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
        //   Statement  DML  
    @Test
    public void testInsert() {
        Statement st = null;
    
        //1.        
        Connection conn = JDBCUtil.getConnection();
    
        try {
            //2.    Statement
            st = conn.createStatement();
    
            //3.   SQL  
            String sql = "insert into WOW(heroName) values('  ')";
    
            //4.   Statement  SQL  
            int count = st.executeUpdate(sql);
    
            //5.      
            System.out.println("count = " + count);
    
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            //conn         ,st      MySQL   SQL     
            //        ,       
            try {
                if (st != null) {
                    st.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }
    
        / /  Statement        
    @Test
    public void testSelect() {
        Connection conn = null;
        Statement st = null;
        ResultSet set = null; //            
        
        try {
            //1.          
            conn = JDBCUtil.getConnection();
            
            //2.   Statement 
            st = conn.createStatement();
            
            //3.   SQL  
            String sql = "select * from WOW";
            
            //4.   SQL   【       】
            set = st.executeQuery(sql);
            
            //5. Result next() getXXX(String    ) XXX         ,
            //                   
            while (set.next()) {
                int heroID = set.getInt("heroID");
                String heroName = set.getString("heroName");
                
                System.out.println(heroID + ":" + heroName);
            }
        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            JDBCUtil.close(conn, st, set);
        }
    }
    

    }