C/C++教程

JDBC preparedStatement 完成增删改

本文主要是介绍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();
                }
            }
        }
    }
}

这篇关于JDBC preparedStatement 完成增删改的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!