1、jdbc每一次创建一个新模块,都需要为该模块重新配置jar包;
2、创建工具类时:属性配文件:db.properties 以及JDBCUtil 工具类放在一个模块中
3、代码实现如下:
##数据库配置信息 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306 jdbc.user=root jdbc.password=root
package com.xzit.platfrom.task.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil {
//获取jdbc驱动
public static String driver;
//jdbc解析地址
public static String url;
//数据库用户名
public static String user;
//数据库密码
public static String password;
static{
//读取配置文件
InputStream resourceAsStream = JDBCUtil.class.getResourceAsStream("db.properties");
try {
//创建properties对象读取属性文件
Properties properties =new Properties();
properties.load(resourceAsStream);
driver=properties.getProperty("jdbc.driver");
url=properties.getProperty("jdbc.url");
user=properties.getProperty("jdbc.user");
password=properties.getProperty("jdbc.password");
//输出:数据库信息
System.out.println("数据库驱动:"+driver);
System.out.println("数据库url:"+url);
System.out.println("数据库用户名:"+user);
System.out.println("数据库密码:"+password);
//获取数据库驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭IO
try {
resourceAsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 创建数据库连接对象
* @return
* @throws Exception
*/
public static Connection getConnection()throws Exception{
return DriverManager.getConnection(url,user,password);
}
/**
* 关闭数据库连接资源
* @param conn
*/
public static void close(Connection conn){
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭接口对象
* @param stmt
*/
public static void close( Statement stmt ){
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭结果集
* @param rs
*/
public static void close( ResultSet rs ){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 创建一个测试文档验证输出结果
* @param args
* @throws Exception
*/
public static void main ( String[] args )throws Exception {
System.out.println(getConnection());
}
}

原创文章,作者:254126420,如若转载,请注明出处:https://blog.ytso.com/tech/database/244810.html