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;
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;
public class JdbcConnectionTool {
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;
}
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();
}
}
}
}
|