JDBC练习二

import java.sql.*;
/*
	JDBC完成Delete
*/

public class JDBCTest02 {
    public static void main(String[] args) {
        // 1、注册驱动
        // 2、获取连接
        // 3、获取数据库操作对象
        // 4、执行sql语句
        // 5、获取查询结果集
        // 6、释放资源

        Connection conn = null;
        Statement stmt = null;
        try {
            Driver driver = new com.mysql.jdbc.Driver();
            DriverManager.registerDriver(driver);

            String url = "jdbc:mysql://127.0.0.1:3306/mydb";
            String user = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url,user,password);

            stmt = conn.createStatement();

            int count = stmt.executeUpdate("delete from student where studentid = 5");

            System.out.println(count == 1? "删除成功":"删除失败");

        } catch(SQLException e){
            e.printStackTrace();
        } finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch(SQLException e){
                    e.printStackTrace();
                }
            }
            if(stmt != null) {
                try {
                    stmt.close();
                } catch(SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

运行结果:

image-20210920190345003

Q.E.D.


樱花庄的一只二刺猿