当前位置: 代码迷 >> 综合 >> JDBC---连接数据库(配置文件)
  详细解决方案

JDBC---连接数据库(配置文件)

热度:78   发布时间:2023-10-21 19:26:38.0

配置文件名:jdbc.properties

name=root
password=
url=jdbc\:mysql\://localhost\:3306/test?characterEncoding\=utf-8
driver=com.mysql.jdbc.Driver

工具类

//package util;import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;public class DBUtil {
    static private String name;static private String password;static private String url;static private String driver;static private Connection connection=null;static {//创建Properties对象Properties p = new Properties();try {//打开配置文件FileInputStream fis = new FileInputStream("src/jdbc.properties");p.load(fis);//加载配置文件name = p.getProperty("name");password = p.getProperty("password");url = p.getProperty("url");driver = p.getProperty("driver");//加载驱动类到内存Class.forName(driver);//获取链接connection = DriverManager.getConnection(url, name, password);} catch (Exception e) {e.printStackTrace();}}//获取链接public static Connection getConnection() {return connection;}//关闭链接public static void close(ResultSet resultSet, Statement statement, Connection connection) {try {if (resultSet != null) {resultSet.close();}if (statement != null) {statement.close();}if (connection != null) {connection.close();}} catch (SQLException e) {e.printStackTrace();}}
}
  相关解决方案