首页 > 数据库技术 > 详细

jdbc原始连接

时间:2019-05-01 15:22:28      阅读:207      评论:0      收藏:0      [点我收藏+]
package cn.hdh.test;

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

import org.junit.Test;

/**
 * 测试查询所有用户的类
 * 
 * @author Administrator
 *
 */
public class QueryAll {

    @Test
    public void testQueryAll() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获取连接
            String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
            String username = "root";
            String password = "12345";
            conn = DriverManager.getConnection(url, username, password);
            // 3.获取执行sql语句对象
            stmt = conn.createStatement();
            // 4.编写sql语句
            String sql = "select * from user";
            // 5.执行sql语句
            rs = stmt.executeQuery(sql);
            // 6.处理结果集
            while (rs.next()) {
                System.out.println("用户名:" + rs.getString(2) + " 密码:" + rs.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null)
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            if (stmt != null)
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}

 

jdbc原始连接

原文:https://www.cnblogs.com/asndxj/p/10799864.html

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