/** * 写一个通用的更新方法 包括 INSERT、 DELETE、UPDATE * 使用工具类 * @param sql */
public void update(String sql){ Connection conn=null; Statement statement=null; try { conn=JDBCTools.getConnection(); statement=conn.createStatement(); statement.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); }finally{ JDBCTools.close(statement, conn); } }
//jdbc工具类
package jdbc; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCTools { /** * 操作JDBC的工具类,其中封装了一些工具方法 版本一; * * @author 杨波波 */ /** * 关闭Statement 和Connection */ public static void close(ResultSet rs, Statement statement, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } public static void close(Statement statement, Connection conn) { if (statement != null) { try { statement.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } /** * 1 获取连接的方法 通过读取配置文件从数据库服务器获取一个连接 * * @return * @throws Exception */ public static Connection getConnection() throws Exception { // 1 准备连接数据库的4个字符串 String driverClass = null; String urljdbc = null; String user = null; String password = null; // 2 读取路径下的配置文件 InputStream is = JDBCTools.class.getClassLoader().getResourceAsStream( "jdbc.properties"); Properties p = new Properties(); p.load(is);// 加载 driverClass = p.getProperty("driver"); urljdbc = p.getProperty("urljdbc"); user = p.getProperty("user"); password = p.getProperty("password"); // // 3 通过反射--->Driver // Driver driver = (Driver) Class.forName(driverClass).newInstance();// // 反射!! // Properties info=new Properties(); // info.put("user",user); // info.put("password", password); // // 通过Driver的connect方法获取数据库的连接 // Connection cc=driver.connect(urljdbc, info); // return cc; // 3 加载数据库的驱动程序(对应的Driver 实现类中有注册驱动的静态代码块) Class.forName(driverClass);// 是的方法灵活 // 4 通过DriverManager的getConnection()方法获取数据库的连接。 Connection cc = DriverManager.getConnection(urljdbc, user, password); return cc; } }
转: https://blog.csdn.net/YL1214012127/article/details/48214093