JDBC模板代码
public class Base {
public static void main(String[] args) {}
static void template() throws Exception {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
//获取连接
con = JDBCUtils.getConnection();
// 创建语句
st = con.createStatement();
// 执行语句
rs = st.executeQuery("MYSQl语句");
// 处理结果
while (rs.next()) {
执行语句......
}
} finally {
//关闭资源
JDBCUtils.free(rs, st, con);
}
}
==============================================================
public final class JDBCUtils {
// 私有的构造器
private JDBCUtils() {}
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "用户名";
private static String password = "密码";
static {
try {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 创建连接
public static Connection getConnection() throws Exception
{
return DriverManager.getConnection(url, user, password);
}
// 断开连接
public static void free(ResultSet rs, Statement st, Connection con)
{
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try {
con.close();
} catch (Exception e2){}
}
}
}
}
==============================================================
/**
* JDBC的单例模式
*/
public final class JDBCUtilsSing {
// 私有的构造器 ,外界不能创建对象
private JDBCUtilsSing() {}
//自己创建自己的对象
private static JDBCUtilsSing instance = new JDBCUtilsSing();
//向外提供获取类对象的方法
public static JDBCUtilsSing getinstance()
{
return instance;
}
private String url = "jdbc:mysql://localhost:3306/jdbc";
private String user = "用户名";
private String password = "密码";
static {
try {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 连接
public Connection getConnection() throws Exception
{
return DriverManager.getConnection(url, user, password);
}
// 断开连接
public void free(ResultSet rs, Statement st, Connection con) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try {
con.close();
} catch (Exception e2){
e2.printStackTrace();
}
}
}
}
}
==============================================================
浙公网安备 33010602011771号