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