cnblogs cat code driver 静态代码块 delete 关闭 oracle
通过 JDBC 向指定的数据表中插入一条记录. 1. Statement: 用于执行 SQL 语句的对象 1). 通过 Connection 的 createStatement() 方法来获取 2). 通过 executeUpdate(sql) 可以执行 SQL 语句. 3). 传入的 SQL 可以是 INSRET, UPDATE 或 DELETE. 但不能是 SELECT 2. Connection、Statement 都是应用程序和数据库服务器的连接资源. 使用后一定要关闭。 需要在 finally 中关闭 Connection 和 Statement 对象. 3. 关闭的顺序是: 先关闭后获取的. 即先关闭 Statement 后关闭 Connection。
封装 jdbc 的基本操作:
- public class JDBCTools {
- public static void release(ResultSet rs,
- Statement statement, Connection conn) {
- if(rs !=null){
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if(statement !=null) {
- try {
- statement.close();
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- if(conn !=null) {
- try {
- conn.close();
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- }
- /**
- * 关闭 Statement 和 Connection
- * @param statement
- * @param conn
- */
- public static void release(Statement statement, Connection conn) {
- if(statement !=null) {
- try {
- statement.close();
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- if(conn !=null) {
- try {
- conn.close();
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- }
- /**
- * 1. 获取连接的方法. 通过读取配置文件从数据库服务器获取一个连接.
- *
- * @return
- * @throws Exception
- */
- public staticConnection 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);
- }
- /**
- * 通用的更新的方法: 包括 INSERT、UPDATE、DELETE
- * 版本 1.
- */
- public void update(String sql){
- Connection conn =null;
- Statement statement =null;
- try {
- conn = getConnection();
- statement = conn.createStatement();
- statement.executeUpdate(sql);
- } catch (Exception e) {
- e.printStackTrace();
- } finally{
- release(statement, conn);
- }
- }
- }
使用的时候通过调用 JDBCTools.java 的 update 方法来进行数据的新增,更新,删除操作
其中 jdbc.properties 文件配置如下:
- #driver=oracle.jdbc.driver.OracleDriver
- #jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
- #user=scott
- #password=java
- driver=com.mysql.jdbc.Driver
- jdbcUrl=jdbc:mysql://localhost:3306/soyoungboyuser=root
- password=1230
Java -- JDBC 学习 -- 通过 Statement 进行数据库更新操作
来源: http://www.bubuko.com/infodetail-2102231.html