博客
关于我
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中使用IN()查询到底走不走索引?
查看>>
Mysql中使用存储过程插入decimal和时间数据递增的模拟数据
查看>>
MySql中关于geometry类型的数据_空的时候如何插入处理_需用null_空字符串插入会报错_Cannot get geometry object from dat---MySql工作笔记003
查看>>
mysql中出现Incorrect DECIMAL value: '0' for column '' at row -1错误解决方案
查看>>
mysql中出现Unit mysql.service could not be found 的解决方法
查看>>
mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>
Mysql中各类锁的机制图文详细解析(全)
查看>>