JDBC:通过 Statement 执行更新操作

本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。


1 Statement 简介

(1) Statement:用于执行 SQL 语句的对象
(2) 通过 Connection 的 createStatement() 方法获取
(3) 通过 executeUpdate(sql) 执行 SQL 语句
(4) 传入的 SQL 可以是 INSERT,UPDATE 和 DELETE,但是不能是 SELECT
(5) Statement 和 Connection 都是应用程序和数据库服务器的连接资源,使用后一定要关闭,需要在 finally 块中关闭,关闭的顺序是先关闭后获取的,即先关闭 Statement 后关闭 Connection

2 准备测试数据库

使用 MySQL 作为测试用数据库,新建 Database Test,在 Test 数据库中新建表 person
这里写图片描述

3 在 Eclipse 中创建测试工程

(1) 在 Eclipse 中新建 Maven Project,添加 JUnit 和 MySQL JDBC 驱动依赖(参看:JDBC:通过 DriverManager 获取数据库连接
生成的 pom 文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>lesson</groupId>
  <artifactId>lesson</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.40</version>
    </dependency>
  </dependencies>
</project>

(2) 在工程 src/main/resources 目录下新建 JDBC 配置文件:jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.user=root
jdbc.password=123456

(3) 编写测试用例

@Test
public void testStatement() {
    java.sql.Connection conn = null;
    java.sql.Statement stmt = null;
    try {
        // 获取数据库连接
        conn = JDBCTool.getConnection("jdbc.properties");
        // 准备插入的SQL
        String sql = "INSERT INTO person(name, email, birth) VALUES ('Jack', 'root@test.com', '2017-1-1 00:00:00')";
        // 获取操作SQL语句的Statement对象,调用Connection的createStatement方法来获取
        stmt = conn.createStatement();
        // 调用Statement对象的executeUpdate(sql)执行SQL语句进行插入
        stmt.executeUpdate(sql);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }
    }
}

(4) JDBCTool getConnection()

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCTool {

    /**
     * 重载的 getConnection()方法
     * @throws IOException 
     * @throws ClassNotFoundException 
     * @throws SQLException 
     */
    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        return getConnection("jdbc.properties");
    }

    /**
     * @throws ClassNotFoundException 
     * @throws SQLException 
     * 
     */
    public static Connection getConnection(String driverClass, String jdbcUrl, String user, String password) throws ClassNotFoundException, SQLException {
        /*
         * 注册驱动:加载数据库驱动程序
         * 实际上执行:DriverManager.registerDriver(new Driver())
         */
        Class.forName(driverClass);
        return DriverManager.getConnection(jdbcUrl, user, password);
    }

    /**
     * @throws IOException 
     * @throws ClassNotFoundException 
     * @throws SQLException 
     * 
     */
    public static Connection getConnection(String propertiesFile) throws IOException, ClassNotFoundException, SQLException {
        // 读取类路径下的jdbc.properties文件
        InputStream in = JDBCTool.class.getClassLoader().getResourceAsStream(propertiesFile);
        Properties info = new Properties();
        info.load(in);
        String driverClass = info.getProperty("jdbc.driver");
        String jdbcUrl = info.getProperty("jdbc.url");
        String user = info.getProperty("jdbc.user");
        String password = info.getProperty("jdbc.password");
        return getConnection(driverClass, jdbcUrl, user, password);
    }

}

(5) 运行测试用例
这里写图片描述

(6) 查询数据库
这里写图片描述

4 提取通用更新数据库方法

/**
 * 通用更新方法:包括INSERT,UPDATE,DELETE
 * @param sql
 */
public static void update(String sql) {
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = getConnection("jdbc.properties");
        stmt = conn.createStatement();
        stmt.executeUpdate(sql);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

5 提取释放数据库资源的方法

/**
 * 关闭数据库连接资源
 */
public static void release(Statement stmt, Connection conn) {
    if (stmt != null) {
        try {
            stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6 使用 JDBCTool 工具类重写单元测试代码

@Test
public void testStatement() {
    java.sql.Connection conn = null;
    java.sql.Statement stmt = null;
    try {
        // 准备插入的SQL
        String sql = "INSERT INTO person(name, email, birth) VALUES ('Jack', 'root@test.com', '2017-1-1 00:00:00')";
        // 调用JDBCTool工具类的update(sql)执行SQL语句进行插入
        JDBCTool.update(sql);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JDBCTool.release(stmt, conn);
    }
}

附:JDBC 工具类

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCTool {

    /**
     * 重载的 getConnection()方法
     * @throws IOException 
     * @throws ClassNotFoundException 
     * @throws SQLException 
     */
    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        return getConnection("jdbc.properties");
    }

    /**
     * @throws ClassNotFoundException 
     * @throws SQLException 
     * 
     */
    public static Connection getConnection(String driverClass, String jdbcUrl, String user, String password) throws ClassNotFoundException, SQLException {
        /*
         * 注册驱动:加载数据库驱动程序
         * 实际上执行:DriverManager.registerDriver(new Driver())
         */
        Class.forName(driverClass);
        return DriverManager.getConnection(jdbcUrl, user, password);
    }

    /**
     * @throws IOException 
     * @throws ClassNotFoundException 
     * @throws SQLException 
     * 
     */
    public static Connection getConnection(String propertiesFile) throws IOException, ClassNotFoundException, SQLException {
        // 读取类路径下的jdbc.properties文件
        InputStream in = JDBCTool.class.getClassLoader().getResourceAsStream(propertiesFile);
        Properties info = new Properties();
        info.load(in);
        String driverClass = info.getProperty("jdbc.driver");
        String jdbcUrl = info.getProperty("jdbc.url");
        String user = info.getProperty("jdbc.user");
        String password = info.getProperty("jdbc.password");
        return getConnection(driverClass, jdbcUrl, user, password);
    }

    /**
     * 通用更新方法:包括INSERT,UPDATE,DELETE
     * @param sql
     */
    public static void update(String sql) {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = getConnection("jdbc.properties");
            stmt = conn.createStatement();
            stmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 关闭数据库连接资源
     */
    public static void release(Statement stmt, Connection conn) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又言又语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值