只需3步。
1、导入mysql的jar包。
略
2、封装配置文件db.properties
driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql:///databaseName?useUnicode=true&characterEncoding=utf8
user = root
password = 123
把数据库驱动和一些数据库参数封装到配置文件,做到随时更换数据库。
3、封装连接代码
/**
* Created by youxuan on 2017/1/15 0015.
* JDBC工具类
*/
public class JDBCUtil {
private static final String driverClass;
private static final String url;
private static final String user;
private static final String password;
static {
try {
InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties pr = new Properties();
pr.load(in);
driverClass = pr.getProperty("driverClass");
url = pr.getProperty("url");
user = pr.getProperty("user");
password = pr.getProperty("password");
Class.forName(driverClass);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
/**
*清理数据库资源
* @param rs
* @param stat
* @param conn
*/
public static void release(ResultSet rs, Statement stat,Connection conn){
try {
if (rs != null) {
rs.close();
}
rs = null;
if(stat != null){
stat.close();
}
stat = null;
if(conn!=null){
conn.close();
}
conn = null;
}catch (Exception e){
e.printStackTrace();
}
}
}
4、连接测试
public void text1(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JDBCUtil.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(" select * from user ");
while(rs.next()){
.......
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JDBCUtil.release(rs, stmt, conn); //关闭数据库资源
}
}