javaweb-demo2

    

 

package com.imooc.jdbc.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

public class JDBCDemo2 {
    @Test

    /**
     * JDBCD释放资源
     */
    public void demo2() {
        // 声明,定义全局变量
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 2.获得链接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "x5");

            // 3.创建执行SQL语句的对象,并执行SQL语句
            // 3.1创建执行SQL语句的对象,并执行SQL语句
            stmt = conn.createStatement();

            String sql = "select * from user";

            // 3.2创建执行SQL语句
            rs = stmt.executeQuery(sql);

            // 3.3遍历数据集
            while (rs.next()) {
                int uid = rs.getInt("uid");
                String username = rs.getString("username");
                String password = rs.getString("password");
                String name = rs.getString("name");

                System.out.println(uid + "," + username + "," + password + "," + name);
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            // 4.释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                rs = null;

            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

 

上一篇:thinkphp-FOR标签


下一篇:字符串切割、截取