Jdbc 对Mysql增删改

package cn.Dong;

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

/**
 * sut 表添加一条记录 insert 语句
 */
/*
    stu表 修改记录
 */
 /**
 *  删除stu    id=6
 */
public class Demo03Jdbc {
    public static void main(String[] args) throws ClassNotFoundException {
        Connection conn = null;
        Statement stmt = null;

        //1.注册驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.定义sql
           // String sql = "update stu set gender='f' where id =6";
           //String sql = "delete from stu where id=6";
            String sql ="insert into stu values(null,'Demo08',12,'f')";
            //3.获取connection对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Mydatabase?useSSL=false&serverTimezone=UTC", "root", "");
            //4.获取执行sql的对象statement
            stmt = conn.createStatement();
            //5.执行sql
            int count = stmt.executeUpdate(sql);//影响的行数
            //6.处理结果
            System.out.println(count);
            if (count > 0) {
                System.out.println("修改成功");

            } else {
                System.out.println("修改失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //stmt.close();
            //7.释放资源
            //避免空指针异常
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

猜你喜欢

转载自blog.csdn.net/DemoD_/article/details/89028382
今日推荐