本文共 1978 字,大约阅读时间需要 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(); } } } 注:该代码已被优化,主要改动包括:
转载地址:http://mwoa.baihongyu.com/