JDBC注册驱动的第二种方法和使用配置文件properties

(1)DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()) —> 反射注册Class.forName(“com.mysql.cj.jdbc.Driver”)

package com.jdbc;
import java.sql.*;
public class JDBCTest03 {
    public static void main(String[] args) {
        try{
            //1.注册驱动
            //注册驱动的第二种方法:常用
            Class.forName("com.mysql.cj.jdbc.Driver");//这个异常对应第一个catch语句块
            //2.获取连接
            //这个异常对应第二个catch语句块SQLException
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=GMT%2B8","root","jh7851192");
            System.out.println(conn);//com.mysql.cj.jdbc.ConnectionImpl@1cbbffcd
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
}

(2)使用配置文件properties获取连接,进行delete/update

//配置文件properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=GMT%2B8
user=root
password=jh7851192
package com.jdbc;
/**
将连接数据库的所有信息配置到配置文件中
* */
import java.util.*;
import java.sql.*;
public class JDBCTest04 {
    public static void main(String[] args) {

        //使用资源绑定器绑定属性配置文件
        ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
        String driver =bundle.getString("driver");
        String url =bundle.getString("url");
        String user =bundle.getString("user");
        String password =bundle.getString("password");

        Connection conn02=null;
        Statement stmt02=null;
        try{
            //1,。注册驱动
            Class.forName(driver);
            //2.获取连接
            conn02=DriverManager.getConnection(url,user,password);
            //3.获取数据库操作对象
            stmt02=conn02.createStatement();
            //4.ִ执行SQL语句
            //String sql02="delete from dept where deptno=109";
            String sql02="update dept set dname='销售部',loc='德国' where deptno=112";
            int count=stmt02.executeUpdate(sql02);
            System.out.println(count==1?"删除成功":"删除失败");
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            //6.释放资源
            if(stmt02!=null){
                try{
                    stmt02.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if(conn02!=null){
                try{
                    conn02.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:String sql02=“update dept set dname=‘销售部’,loc=‘德国’ where deptno=112”;
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值