共计 831 个字符,预计需要花费 3 分钟才能阅读完成。
一、JdbcUtils 的作用
前面我们学了,连接数据库的四大参数是:驱动类、url、用户名,以及密码。这些参数都与特定数据库关联,如果将来想更改数据库,那么就要去修改这四大参数,那么为了不去修改代码,我们写一个 JdbcUtils 类,让它从配置文件中读取配置参数,然后创建连接对象。
二、JdbcUtils 代码
JdbcUtils.java
public class JdbcUtils {private static final String dbconfig = "dbconfig.properties" ; | |
private static Properties prop = new Properties() ; | |
static {try {InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(dbconfig); | |
prop.load(in); | |
Class.forName(prop.getProperty("driverClassName")); | |
} catch(IOException e) {throw new RuntimeException(e); | |
} | |
} | |
public static Connection getConnection () {try {return DriverManager.getConnection(prop.getProperty("url"), | |
prop.getProperty("username"), prop.getProperty("password")); | |
} catch (Exception e) {throw new RuntimeException(e); | |
} | |
} | |
} | |
dbconfig.properties
driverClassName=com.mysql.jdbc.Driver | |
url=jdbc:mysql://localhost:3306/mydb1 | |
username=root | |
password=123 |
正文完
星哥玩云-微信公众号
