8.13文件操作

1.删除

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

public class TestDelete {
    public static void main(String[] args){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        DBUtil dbUtil=null;
        //1.加载驱动
        try {
            dbUtil=new DBUtil();
            connection=dbUtil.getConnection();

        //3.写sql
        String sql="delete student where id=?";
        //4.获得startment对象
          preparedStatement=connection.prepareStatement(sql);
          preparedStatement.setInt(1,2);
          preparedStatement.executeUpdate();
        }catch (Exception e){
        e.printStackTrace();
        }finally {
                  dbUtil.closeAll(null,preparedStatement,connection);
        //5.得到结果集
             }
        //6.处理结果集
        //7.关闭资源
    }
}

2.DBUtil

import java.sql.*;

public class DBUtil {
    public static Connection getConnection(){
        Connection connection=null;
        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            connection = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/ningda?useSSL=true&characterEncoding=utf-8&user=root&password=root");
            System.out.println("创建连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeAll(ResultSet rs, PreparedStatement preparedStatement,Connection connection){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}

猜你喜欢

转载自blog.csdn.net/zlc2351951436/article/details/99550175