Java教程

javaweb-demo2

本文主要是介绍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();
                }
            }
        }
    }
}

 

这篇关于javaweb-demo2的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!