日期:2014-05-16 浏览次数:20405 次
package cn.guangpeng.jdbc; public class TestResultSet { public static void main(String[] args) throws Exception { Connection connection = null; Statement st = null; ResultSet rs = null; try { connection = getConnection(); st = connection.createStatement(); String sql = "SELECT id, age,name FROM customer"; rs = st.executeQuery(sql); while (rs.next()) { // 1,2,3分别为为每列所对应的字段 String id = rs.getString(1); String age = rs.getString(2); String name = rs.getString(3); System.out.println("id :" + id + ", age :" + age + ", name :" + name); } } finally { // 最后一定要关闭连接 releaseResource(connection, st, rs); } } //先打开的链接后断开,就和人脱衣服一样,先穿的后脱,呵呵 private static void releaseResource(Connection connection, Statement st, ResultSet rs) throws Exception { try { if (rs != null) rs.close(); } finally { try { if(st != null) st.close(); } finally { if (connection != null) connection.close(); } } } private static Connection getConnection() throws Exception { // 准备四个必须的数据 String driverClass = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/itcast"; // jdbc: 协议名, mysql: 子协议名, localhost:3306/itcast: 子名称 // localhost:数据库服务器的 ip, 3306 数据库服务器的端口号, itcast: 数据库名 String user = "root"; String password = "root"; // 2.加载数据库的驱动程序,实例化 Class.forName(driverClass); // 3. 调用 DriverManager 的 getConnection(url, user, password) 获取数据库连接 Connection connection = DriverManager.getConnection(url, user, password); return connection; } }