一、步骤说明
1.加载驱动
2.创建数据库连接
3.创建语句对象
4.创建sql
5.执行sql返回执行结果
6.关闭数据库资源
二、代码实现
package com.sjsq.dao; import java.sql.*; /** * Java中使用JDBC连接数据库 * @author shuijianshiqing * @date 2020/6/18 18:40 */ public class DBUtil { // JDBC Driver static final String JDEC_DRIVER = "com.mysql.cj.jdbc.Driver"; // URL(注意Mysql8.0只后需要添加时区信息) static final String DB_URL = "jdbc:mysql://localhost/demo?serverTimezone=UTC"; // 账号 static final String USER = "root"; // 密码 static final String PASS = "admin"; public static void main(String[] args){ // 定义Connection Connection conn = null; // 定义Statement Statement stmt = null; try{ // 1.加载驱动 Class.forName(JDEC_DRIVER); System.out.println("连接数据库"); // 2.创建数据库连接 conn = DriverManager.getConnection(DB_URL,USER,PASS); System.out.println("创建Statement对象"); // 3.创建语句对象 // Statement对象用于将 SQL 语句发送到数据库中,执行对数据库的数据的检索或者更新。 stmt = conn.createStatement(); // 4.创建sql String sql; sql = "select * from user"; // 5.处理执行结果,执行sql,将结果保存在rs里面 ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { String username = rs.getString("username"); String password = rs.getString("password"); System.out.println("name:" + username); System.out.println("password:" + password); } // 6.关闭资源 rs.close(); stmt.close(); conn.close(); } catch(SQLException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try { if(stmt != null) { stmt.close(); } } catch(SQLException e) { e.printStackTrace(); } } System.out.println("数据库已关闭"); } }