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”;
在这里插入图片描述

发布了42 篇原创文章 · 获赞 8 · 访问量 2446

猜你喜欢

转载自blog.csdn.net/JH39456194/article/details/103336774