JDBC day01

什么是JDBC

java连接数据库的规范

JDBC核心思想

java定义了访问数据库的接口 可为多种关系型数据库提供统一的访问方式

JDBC开发步骤

1 导包 注册驱动

Class.forName(" com.mysql.jdbc.Driver ")

2 获取数据库连接对象

DriverManager.getConnection("jdbc:mysql://localhost :3306/数据库名","username","password")

3 准备sql语句

String sql="";

4 获取执行对象

Statement

5执行sql

如果是DQL语句用executequery

如果是DML语句用executeupdate

6 处理结果

如果是查询 返回修改的Resultset结果集

如果是增删改 返回的是修改的行数

7释放资源

也可以封装成工具类 方便调用

先编写配置文件

在src目录下 创建 resource 文件

eg

driverclassname=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/my2203?useSSL=false
username=root
password=1234

在工具类中 创建 properties集合读取配置文件 到prop集合

eg:

InputStream inputStream = conjdbc.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties prop= new Properties();
prop.load(inputStream);

根据键获取值

driverclassname =prop.getProperty("driverclassname");
url= prop.getProperty("url");
username= prop.getProperty("username");
password=prop.getProperty("password");

第一步先注册驱动

Class.forName(driverclassname);

上面这些都在静态代码块内执行

第二步创建一个返回值为连接对象的方法

eg

public static Connection getconnection( ) throws SQLException {
    Connection connection = DriverManager.getConnection(url, username, password);
    return connection;
}

第三步创建一个释放资源的方法

eg:

public static void close(Statement stat,Connection conn){
    close(null,stat,conn);
}

public static void close(ResultSet rs, Statement sta,Connection conn){
    if(rs!=null){
        try {
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if(sta!=null){
        try {
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if(conn!=null){
        try {
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值