最简单的一个java驱动jdbc链接mysql数据库

导入jar包:mysql.connector-java-5.0.8-bin.jar

        String driver = "com.mysql.jdbc.Driver";
        String url= "jdbc:mysql://127.0.0.1:3306/ali";
        Connection conn = null;
        
        try {
            Class.forName(driver);
            conn =     DriverManager.getConnection(url, "root", "");
            //System.out.println(conn);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 

        ResultSet  rs = null;  
        PreparedStatement ps = null;
        String sql = "select * from think_user;";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                System.out.println(rs.getString("id"));
                System.out.println(rs.getString("username"));
                System.out.println(rs.getString("turename"));
            }        
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 

 

最后一定要记得 关闭链接哦!!

 

posted @ 2017-04-07 19:03  与f  阅读(1200)  评论(0编辑  收藏  举报