自己封装了一个JDBC类,已测试
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLDataException;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Statement;
public class JDBCUtils {
static Properties properties = null;
/* private final static String URL = "jdbc:mysql://localhost:3306/***";
private final static String USER = "***";
private final static String PASSWORD = "***";
private final static String JDBCDRIVER = "com.mysql.jdbc.Driver";*/
private JDBCUtils() {}
//注册驱动
static {
try {
properties = new Properties();
try {
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
} catch (IOException e) {
System.out.println(JDBCUtils.class + "properties.load() error");
}
Class clazz = Class.forName(properties.getProperty("DBDRIVER"));
}
catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
if(properties != null && !properties.getProperty("DBURL").isEmpty()
&& !properties.getProperty("DBUSER").isEmpty()
&& !properties.getProperty("DBPASSWORD").isEmpty()) {
return DriverManager.getConnection(properties.getProperty("DBURL"),
properties.getProperty("DBUSER"), properties.getProperty("DBPASSWORD"));
}
return null;
}
//释放资源
public static void close(Connection con, Statement ps, ResultSet rs) {
closeConnection(con);
closeStatement(ps);
closeResultSet(rs);
}
public static void close(Connection con, Statement ps) {
closeConnection(con);
closeStatement(ps);
}
//释放连接 Connection
public static void closeConnection(Connection con) {
if(con != null) {
try {
con.close();
} catch (SQLException e) {
System.err.println("释放连接 Connection 异常");
e.printStackTrace();
}
}
con = null;
}
//释放 Statement
public static void closeStatement(Statement ps) {
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
System.err.println("释放 Statement 异常");
e.printStackTrace();
}
}
ps = null;
}
//释放 ResultSet
public static void closeResultSet(ResultSet rs) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
System.err.println("释放 ResultSet 异常");
e.printStackTrace();
}
}
rs = null;
}
}
db.properties
*号的地方自己替换成自己的就可以了
DBDRIVER:com.mysql.jdbc.Driver
DBURL:jdbc:mysql://localhost:3306/***
DBUSER:***
DBPASSWORD:***