JDBC properties配置文件

一、使用properties配置文件

       开发中获得连接的4个参数(驱动、URL、用户名、密码)通常都存在配置文件中,方便后期维护,程序如果需要更换数据库,只需要修改配置文件即可。

       通常情况下,我们习惯使用properties文件,此文件我们将做如下要求:

       1. 文件位置:任意,建议src下

       2. 文件名称:任意,扩展名为properties

       3. 文件内容:一行一组数据,格式是“key=value”.

          ①key命名自定义,如果是多个单词,习惯使用点分隔。例如:jdbc.driver

          ②value值不支持中文,如果需要使用非英文字符,将进行unicode转换。

 

二、创建配置文件

在项目跟目录下,创建文件,输入“db.properties”文件名。

文件中的内容

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/mydb

user=root

password=root

 

三、加载配置文件:Properties对象

       对应properties文件处理,开发中也使用Properties对象进行。我们将采用加载properties文件获得流,然后使用Properties对象进行处理。

JDBCUtils.java中编写代码

public class JDBCUtils {

 

    private static String driver;

    private static String url;

    private static String user;

    private static String password;

    // 静态代码块

    static {

        try {

            // 1 使用Properties处理流

            // 使用load()方法加载指定的流

            Properties props = new Properties();

            Reader is = new FileReader("db.properties");

            props.load(is);

            // 2 使用getProperty(key),通过key获得需要的值,

            driver = props.getProperty("driver");

            url = props.getProperty("url");

            user = props.getProperty("user");

            password = props.getProperty("password");

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

 

    /**

     * 获得连接

     */

    public static Connection getConnection() {

        try {

            // 1 注册驱动

            Class.forName(driver);

            // 2 获得连接

            Connection conn = DriverManager.getConnection(url, user, password);

            return conn;

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

}

 

四、使用JDBCUtils工具类

测试类

public class Demo {

    @Test

    public void insert(){

        try{

            //1,获取连接对象

            Connection conn = JDBCUtils.getConnection();

            //2,指定要执行的SQL语句

            String sql = "INSERT INTO zhangwu(name,money,parent) VALUES(?,?,?)";

            //4,获取SQL语句的执行对象 PreparedStatement

            PreparedStatement ppstat = conn.prepareStatement(sql);

            //5,执行SQL语句

            ppstat.setString(1, "股票收入");

            ppstat.setDouble(2, 5000);

            ppstat.setString(3, "收入");

            int line = ppstat.executeUpdate();

            //6,处理结果集

            System.out.println("line=" + line);

            //7,关闭连接

            ppstat.close();

            conn.close();

        } catch(SQLException e){

            throw new RuntimeException(e);

        }

    }

}

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值