首页 > 数据库技术 > 详细

完整使用JDBC访问数据库

时间:2017-05-17 13:08:19      阅读:234      评论:0      收藏:0      [点我收藏+]

Connection con = null;
PreparedStatement statement = null;
ResultSet res = null;

List<Student> students = new ArrayList<Student>();

List<Student> getAll() {

try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            statement = (PreparedStatement) con.createStatement();
            res = statement.executeQuery("SELECT * FROM students");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            while(res.next()){
                String name = res.getString(1);
                int age = res.getInt(2);
Student student = new Student(name,age); students.add(student); } }
catch (SQLException e1) { e1.printStackTrace(); } if (res != null) { try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return students; }

 

完整使用JDBC访问数据库

原文:http://www.cnblogs.com/20158424-hxlz/p/6866883.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!