jdbc 04: 配置连接信息

jdbc连接mysql,将需要的信息配置到文件中

package com.examples.jdbc.o4_配置连接信息;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

/*
    将连接数据库所需要的信息全部写到配置文件中
 */
public class Test {
    public static void main(String[] args) {
        resourceBundle();
    }

    //通过资源绑定器绑定属性配置文件
    public static void resourceBundle(){

        //获取指定配置文件的资源绑定器
        ResourceBundle resourceBundle = ResourceBundle.getBundle("config/jdbc");

        String driver = resourceBundle.getString("driver");
        String url = resourceBundle.getString("url");
        String userName = resourceBundle.getString("userName");
        String passWord = resourceBundle.getString("passWord");

        Connection connection = null;
        Statement statement = null;
        try {
            //1.(常用注册驱动的方法)
            Class.forName(driver);

            //2.
            connection = DriverManager.getConnection(url, userName, passWord);

            //3.
            statement = connection.createStatement();

            //4.
            String sql = "update student set sname = '郭郭' where sname = 'wangxun'";
            int num = statement.executeUpdate(sql);
            System.out.println(num == 1 ? "修改成功" : "修改失败");

            //5.

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            //6.
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

配置文件的信息

文件名:jdbc.properties
文件内容

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://ip/数据库名
userName=用户名
passWord=密码
posted @   nefu-xun  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示