您的位置:首页 > 数据库

基于Properties实现配置数据库驱动

2020-05-07 04:05 232 查看

优点:

便于修改连接属性。只需在配置文件中修改,不需要在代码中修改了。 更易于维护代码安全性。

方法:

在src文件嘉下创建database.properties文本文件;添加内容:

driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/y1
name=root
password=root

创建工具类MyJDBCUtiles.java,添加代码:  

package com.kong.JDBCUtils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class MyJDBCUtiles {
private MyJDBCUtiles(){}
private static Connection con;
private static String driver;
private static String url;
private static String name;
private static String password;
static{
try {
InputStream is = MyJDBCUtiles.class.getClassLoader().getResourceAsStream("database.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
name = properties.getProperty("name");
password = properties.getProperty("password");
Class.forName(driver);
con = DriverManager.getConnection(url, name, password);
}catch (Exception ep){
throw new RuntimeException(ep+"数据库连接失败");
}
}
public static Connection getConnection(){
return con;
}

其他类使用时调用即可

输出结果

完美^_^

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐