码迷,mamicode.com
首页 > 数据库 > 详细

完整使用JDBC访问数据库

时间:2017-05-17 14:15:20      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:tco   cal   1.5   drive   res   list   .exe   driver   mysql   

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访问数据库

标签:tco   cal   1.5   drive   res   list   .exe   driver   mysql   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!