博客
关于我
jdbc操作数据库基础: 查询的例子
阅读量:259 次
发布时间:2019-03-01

本文共 1869 字,大约阅读时间需要 6 分钟。

package org.example.jdbc;import java.sql.*;public class FirstExample {    // 数据库信息    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";    static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT";    // 用户名、密码    static final String USER = "root";    static final String PASS = "jianan";    public static void main(String[] args) {        Connection conn = null;        Statement stmt = null;        ResultSet rs = null;        try {            // 加载数据库驱动            Class.forName(JDBC_DRIVER);            // 连接数据库            conn = DriverManager.getConnection(DB_URL, USER, PASS);            // 执行sql            stmt = conn.createStatement();            String sql = "SELECT id, age, first, last FROM Employees";            rs = stmt.executeQuery(sql);            // 遍历结果集            while (rs.next()) {                int id = rs.getInt("id");                int age = rs.getInt("age");                String first = rs.getString("first");                String last = rs.getString("last");                System.out.printf("%d,%d,%s,%s", id, age, first, last);            }        } catch (Exception e) {            e.printStackTrace();        } finally {            // 释放数据库相关资源            try {                if (rs != null) {                    rs.close();                }            } catch (SQLException e) {                e.printStackTrace();            }            try {                if (stmt != null) {                    stmt.close();                }            } catch (SQLException e) {                e.printStackTrace();            }            try {                if (conn != null) {                    conn.close();                }            } catch (SQLException e) {                e.printStackTrace();            }        }    }}/*1,28,贾,楠2,29,孙,晨曦*/

 

转载地址:http://mwoa.baihongyu.com/

你可能感兴趣的文章
2016年省赛a组
查看>>
string字符串中转义,调用类方法
查看>>
后台管理系统项目总结(下)
查看>>
scala上界与下界、协变与逆变
查看>>
java稀疏数组
查看>>
compare排序原理
查看>>
MYSQL远程连接不上的解决方法
查看>>
springboot解决前后端交互跨域问题
查看>>
宝马、沃尔沃、奇瑞纷纷布局,区块链将颠覆汽车行业?
查看>>
全球数字货币加快研发
查看>>
数字化助力金融科技,实现产业良性循环
查看>>
2020-11-16(常见加密算法统计)
查看>>
2020-11-18(失败的一天)
查看>>
2020-11-23(彻底理解KMP)
查看>>
DMB DSB ISB 简介
查看>>
常用的IDC函数
查看>>
BUUCTF 新年快乐 内涵的软件 Java逆向解密 刮开有奖
查看>>
虎符杯——虚拟机逆向
查看>>
angr学习笔记(3)
查看>>
angr学习笔记(7)(malloc地址单元符号化)
查看>>