JDBC Statement 更新和删除数据


数据库和表设计

-- 创建数据库
CREATE DATABASE `bank`;

-- 切换到 bank 库
USE `bank`;

-- 创建表
CREATE TABLE `user_balance` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NOT NULL ,
  `balance` BIGINT NOT NULL ,
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_general_ci;

user_balance 表中准备两条数据:

mysql> select * from user_balance;
+----+--------+---------+
| id | name   | balance |
+----+--------+---------+
|  1 | letian |    1000 |
|  2 | xiaosi |    1001 |
+----+--------+---------+
2 rows in set (0.00 sec)

使用 JDBC Statement 更新和修改数据

package demo;

import java.sql.*;

/**
 * 使用 Statement 更新和删除数据
 */
public class StatementUpdateAndDelete {

    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/bank";

    /**
     * 根据name更新balance
     */
    public static void update(String name, Long balance) throws ClassNotFoundException, SQLException {
        Class.forName(JDBC_DRIVER);
        Connection conn =  DriverManager.getConnection(DB_URL, USER, PASSWORD);
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            String sql = String.format("UPDATE user_balance SET balance=%s WHERE name='%s'", balance, name);
            int affectRowsNum = stmt.executeUpdate(sql);
            System.out.println("影响的行数:" + affectRowsNum);
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            conn.close();
        }
    }

    /**
     * 根据 name 删除数据
     */
    public static void delete(String name) throws ClassNotFoundException, SQLException {
        Class.forName(JDBC_DRIVER);
        Connection conn =  DriverManager.getConnection(DB_URL, USER, PASSWORD);
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            String sql = String.format("DELETE FROM user_balance where name='%s'", name);
            int affectRowsNum = stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            System.out.println("影响的行数:" + affectRowsNum);
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            conn.close();
        }
    }


    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        update("letian", 1002L);
        delete("xiaosi");
    }
}

运行后输出:

影响的行数:1
影响的行数:1

查看 user_balance表中内容:

mysql> select * from user_balance;
+----+--------+---------+
| id | name   | balance |
+----+--------+---------+
|  1 | letian |    1002 |
+----+--------+---------+
1 row in set (0.00 sec)

可以看到 name 为 xiaosi 的记录被删掉了。name 为 letian 的记录的balance变成了1002



(本文完)


JDBC 教程