- 配置文件:db.properties
//驱动名
driverClass=com.mysql.jdbc.Driver
//homework为数据库名
url=jdbc:mysql://localhost:3306/homework
//mysql账号
username=root
//密码
password=1997
- 工具类:JDBCUtil
package jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtil {
//定义需要的常量
private static final String driverClassName;
private static final String url;
private static final String username;
private static final String password;
//通过静态代码块加载配置文件中的数据
static {
Properties pp = new Properties();
try {
pp.load(new FileInputStream("src/db.properties"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driverClassName=pp.getProperty("driverClass");
url = pp.getProperty("url");
username =pp.getProperty("username");
password = pp.getProperty("password");
}
/*
* 加载驱动的方法
*/
public static void loadDriver() {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 获取连接的方法
*/
public static Connection getConnection(){
//加载驱动
loadDriver(