JDBC 通过Statement 执行更新操作 2.1
/*
* 通过的更新方法:包括 insert、update、delete
*
*/
public void update(String sql) {
Connection conn = null;
Statement statement = null;
try {
conn = getConnection2();
statement = conn.createStatement();
statement.executeUpdate(sql);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
// JDBCtools.release(statement,conn);
// 下面的全部可以替换为这一句话
if(statement != null) {
try {
statement.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
新建 JDBCtools 类
(工具类)
/*
* 操作 JDBC 的工具类,其中封装了一些工具方法
* version 1
*
*/
public class JDBCtools {
/*
* 关闭 Statement 和 Conncetion
*/
public static void release(Statement statement,Connection conn) {
if(statement != null) {
try {
statement.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
public static Connection getConnection() throws Exception {
// 1. 准备连接数据库的 4 个字符串
// 1) 创建 Properties 对象
Properties properties = new Properties();
// 2) 获取 jdbc.properties 对应的输入流
InputStream in = JDBCtools.class.getClassLoader().getResourceAsStream("jdbc.properties");
// 3)加载 2)对应的输入流
properties.load(in);
// 4) 具体决定 user password 等 4 个字符串
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driver = properties.getProperty("driver");
// 2. 加载 数据库驱动程序(对应的Driver 实现类中有注册驱动的静态代码块 )
Class.forName(driver);
// 3. 通过 DriverManager 的getConnection() 方法获取数据库连接
return DriverManager.getConnection(jdbcUrl, user, password);
}
}

浙公网安备 33010602011771号