数据库配置文件以及连接工具类编写

1、数据库配置文件书写

   建立db.properties,书写内容如下

//数据库驱动的名称,可以根据不同的数据库进行相应的修改
driver=com.mysql.jdbc.Driver
//数据库的url,字符集需要添加,否则查询数据有可能因为乱码导致查询不到
url=jdbc:mysql://localhost:3306/shop?characterEncoding=utf-8&serverTimezone=UTC
//数据库用户名
user=root
//数据库密码
password=root
其中url写法:
jdbc:mysql:[]//localhost:3306/shop?参数名:参数值
协议 子协议 主机 端口 数据库
其他数据库url书Oracle写法:jdbc:oracle:thin:@localhost:1521:sid

SqlServer—jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sid
MySql—jdbc:mysql://localhost:3306/sid
Mysql的url地址的简写形式: jdbc:mysql:///sid
常用属性:useUnicode=true&characterEncoding=UTF-8

 2、数据库工具类编写

  新建DBUtil文件

  数据库连接步骤:

1、读取配置文件
2、加载数据库驱动
3、获取数据库连接
4、关闭数据库连接,释放资源
/**
* 数据库连接工具类
*/
public class DBUtil {
//1、读取配置文件
//2、加载数据库驱动
//3、获取数据库连接
//4、关闭数据库连接,释放资源
private static Properties properties = new Properties();
//加载配置文件
static {
String path = DBUtil.class.getClassLoader().getResource("db.properties").getPath();
try {
properties.load(new FileInputStream(path));
} catch (IOException e) {
e.printStackTrace();
}
}
//获得连接
//注册驱动
public static Connection getConn(){
Connection connection = null;
try {
Class.forName(properties.getProperty("driver"));
connection = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("user"),properties.getProperty("password"));
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//释放资源
public static void release(Connection connection,Statement statement,ResultSet resultSet){
//结果集
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//声明
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//连接
if(connection !=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


 

  

  

原文地址:https://www.cnblogs.com/wuhao-0206/p/12614867.html