博客
关于我
jdbc操作数据库基础: 查询的例子
阅读量:265 次
发布时间: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/

你可能感兴趣的文章
MySQL 触发器
查看>>
mysql 让所有IP访问数据库
查看>>
mysql 记录的增删改查
查看>>
MySQL 设置数据库的隔离级别
查看>>
MySQL 证明为什么用limit时,offset很大会影响性能
查看>>
Mysql 语句操作索引SQL语句
查看>>
MySQL 误操作后数据恢复(update,delete忘加where条件)
查看>>
MySQL 调优/优化的 101 个建议!
查看>>
mysql 转义字符用法_MySql 转义字符的使用说明
查看>>
mysql 输入密码秒退
查看>>
mysql 递归查找父节点_MySQL递归查询树状表的子节点、父节点具体实现
查看>>
mysql 通过查看mysql 配置参数、状态来优化你的mysql
查看>>
mysql 里对root及普通用户赋权及更改密码的一些命令
查看>>
Mysql 重置自增列的开始序号
查看>>
mysql 锁机制 mvcc_Mysql性能优化-事务、锁和MVCC
查看>>
MySQL 错误
查看>>
mysql 随机数 rand使用
查看>>
MySQL 面试题汇总
查看>>
MySQL 面试,必须掌握的 8 大核心点
查看>>
MySQL 高可用性之keepalived+mysql双主
查看>>