JDBC入门

2022-11-16 09:20:13 浏览数 (1)

JDBC开发流程

  1. 加载并注册JDBC驱动 
  2. 创建数据库连接
  3. 创建Statement对象
  4. 遍历查询结果
  5. 关闭连接,释放资源

示例代码

代码语言:javascript复制
package com.imooc.jdbc.sample;

import java.sql.*;


public class StandardJDBCSample {
    public static void main(String[] args) {
        Connection conn = null;
        try {
            //1. 加载并注册JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2. 创建数据库连接
            conn = DriverManager.getConnection(
                    //数据库URL
                    "jdbc:mysql://localhost:3306/imooc?useSSL=false&useUmicode=ture&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai",
                    //数据库用户名
                    "username",
                    //数据库密码
                    "password"
            );
            //3. 创建Statemetnt对象
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from employee where dname = '研发部'");
            //4. 遍历查询结果
            while (rs.next()){
                Integer eno = rs.getInt(1);//eno
                String ename = rs.getString("ename");
                Float salary = rs.getFloat("salary");
                String dname = rs.getString("dname");
                System.out.println(eno   "-"   ename   "-"   salary   "-"   dname);
            };
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //5. 关闭连接,释放资源
            try {
                if (conn != null && conn.isClosed() == false){
                    conn.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

0 人点赞