JDBC连接数据库的两种方式
package jess.day15;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* @author Jess
* @date 2021/10/19
*/
public class Conn {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
conn2();
}
/**
* 直接读取字符串
*/
public static void conn1() {
String url = "jdbc:mysql://127.0.0.1:3306/jzy1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
String name = "root";
String password = "123456";
String driver = "com.mysql.cj.jdbc.Driver";
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, name, password);
System.out.println(connection);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
/**
* 通过配置文件读取
*/
public static void conn2() throws IOException, ClassNotFoundException, SQLException {
Properties properties =new Properties();
// 读取配置文件
properties.load(new FileInputStream("jdbc.properties"));
// 解析配置文件
String url = properties.getProperty("url");
String name = properties.getProperty("name");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
System.out.println(url);
// 加载驱动
Class.forName(driver);
// 获取连接
Connection connection = DriverManager.getConnection(url, name, password);
System.out.println(connection);
}
}
properties配置文件
url =jdbc:mysql://127.0.0.1/jzy2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
name =root
password =123456
driver =com.mysql.cj.jdbc.Driver
连接数据库的工具类
package cn.jess.day02;
import cn.jess.day01.JdbcTest;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* 连接数据库
* @author Jess
*/
public class JdbcConnectionTool {
/**
* 获取连接
* @return 连接对象
*/
public static Connection getConnection() {
Properties properties = new Properties();
Connection con = null;
try {
//加载配置文件
properties.load(JdbcTest.class.getClassLoader().getResourceAsStream("jdbc.properties"));
// 读取配置文件
String url = properties.getProperty("mysql.url");
String user = properties.getProperty("mysql.username");
String password = properties.getProperty("mysql.password");
//获取连接
con = DriverManager.getConnection(url, user, password);
} catch (IOException | SQLException e) {
e.printStackTrace();
}
return con;
}
/**
* 关闭资源
* @param statement
* @param connection
* @param resultSet
*/
public static void connClose(Statement statement,Connection connection,ResultSet resultSet){
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}