jdbc的学习2(删、改)

wuchangjian2021-11-24 10:15:23编程学习

删除与修改跟增加只是sql语句的更改而已

package com.msb.test1;

import java.sql.*;

public class TestJDBC2 {
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://127.0.0.1:3306/green?UseSSL=false&&useUnicode=true&&charecterEncoding=UTF-8&ServerTimezone=Asia/shanghai";
    private static String user = "root";
    private static String password = "root";
    public static void main(String[] args){
        //testDele();
        testUpdate();
    }
    //删除
    public static void testDele(){
        Statement statement = null;
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
            statement = connection.createStatement();
            String sql = "delete from activity where activity_id = 1";
            int rows = statement.executeUpdate(sql);
            System.out.println("影响行数为:" + rows);
          }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != statement) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //修改
    public static void testUpdate(){
        Statement statement = null;
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
            statement = connection.createStatement();
            String sql = "update activity set user_account = '单',the_city_name='深圳' where activity_id=2";
            int rows = statement.executeUpdate(sql);
            System.out.println("影响行数为:" + rows);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != statement) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。