JDBC preparedStatement 完成增删改

package com.mxy.jdbc;

/*
    PreparedStatement完成INSERT DELETE UPDATE
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCTest09 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "123456");
            //3.获取预编译的数据库操作对象
            /*String sql = "insert into grade(id, gra_name) values(?, ?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, 5);
            ps.setString(2, "15级");*/

            /*String sql = "update grade set gra_name = ? where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "测试级!");
            ps.setInt(2, 3);*/

            String sql = "delete from grade where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, 3);

            //4.执行sql
            int count = ps.executeUpdate();
            System.out.println(count);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

上一篇:解决SQL注入问题


下一篇:Java开启事务之MySQL数据库