配置文件名: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();}}
}