MySQL——statement对象详解

JDBC中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。

Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完成后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。

Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

CRUD操作-create

使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

java 复制代码
Statement st = conn.createStatement();
String sql = "insert into user(... .) values(... . .)"
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("插入成功!");
}

CRUD操作-delete

使用executeUpdate(String sql)方法完成数据删除操作,示例操作:

java 复制代码
Statement st = conn.createStatement();
String sql = "delete from user where id=1"
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("删除成功!");
}

CRUD操作-update

使用executeUpdate(String sql)方法完成数据修改操作,示例操作:

java 复制代码
Statement st = conn.createStatement();
String sql = "update user set name='' where name=''"
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("修改成功!");
}

CRUD操作-read

使用executeQuery(String sql)方法完成数据查询操作,示例操作:

java 复制代码
Statement st = conn.createStatement();
String sql = "select * from user where id=1"
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
    // 根据获取列的数据类型,分别调用rs的相应方法映射到java对象中
}

代码实现

  1. 提取工具类
java 复制代码
public class jdbcUtils {

    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {

        try {
            InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");// 获取具体资源
            Properties properties = new Properties();
            properties.load(in);

            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

            // 1.驱动只用加载一次
            Class.forName(driver);

        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    // 获取连接
    public  static Connection  getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }

    // 释放连接资源
    public static void release(Connection conn, Statement stmt, ResultSet rs) throws SQLException {
        if (rs!=null){
            rs.close();
        }
        if (stmt!=null){
            stmt.close();
        }
        if (conn!=null){
            conn.close();
        }
    }

}
  1. 编写增删改的方法,executeUpdate

增:

java 复制代码
public class TestInsert {
    public static void main(String[] args) throws SQLException {

        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            conn = jdbcUtils.getConnection();  // 获取数据库连接
            st = conn.createStatement();  // 获得SQL的执行对象
            String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" +
                    "VALUES(4,'chenyang','123456','888@qq.com','2024-7-5')";

            int i = st.executeUpdate(sql);
            if (i>0){
                System.out.println("插入成功!");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbcUtils.release(conn,st,rs);
        }
    }
}

删:

java 复制代码
public class TestDelete {
    public static void main(String[] args) throws SQLException {

        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            conn = jdbcUtils.getConnection();
            st = conn.createStatement();
            String sql = "DELETE FROM users WHERE id=4";

            int i = st.executeUpdate(sql);

            if (i>0){
                System.out.println("删除成功!");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbcUtils.release(conn,st,rs);
        }
    }

改:

java 复制代码
public class TestUpdate {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            conn = jdbcUtils.getConnection();
            st = conn.createStatement();
            String sql = "UPDATE users SET `NAME`='chenyang8' WHERE id=4";

            int i = st.executeUpdate(sql);

            if (i>0){
                System.out.println("修改成功!");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbcUtils.release(conn,st,rs);
        }
    }
}
  1. 查询,executeQuery
java 复制代码
public class TestSelect {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            conn = jdbcUtils.getConnection();
            st = conn.createStatement();
            //SQl
            String sql = "select * from users where id = 1";
            rs = st.executeQuery(sql);  //查询完毕会返回一个结果集

            if (rs.next()){
                System.out.println(rs.getString("NAME"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbcUtils.release(conn,st,rs);
        }

    }
}
相关推荐
星恒讯工业路由器4 分钟前
工业网络设备选型:导轨式、机架式与车载式的部署差异
开发语言·网络·数据库·php·工业路由器·导轨式·车载式
wespaul3 小时前
VeapAI 自然语言操作实战|第 05 篇:向量与召回——从知识条目到可检索资产
大数据·数据库·人工智能·milvus
一只鹿鹿鹿8 小时前
政务外网整体设计方案(PPT)
大数据·数据库·web安全·系统安全·流程图·政务
2603_965148118 小时前
社区与学习资源:从入门到精通的API选品学习路径
数据库·人工智能·python·学习·数据挖掘
for_ever_love__8 小时前
MySQL ORDER BY 排序优化:从 Using filesort 到索引有序扫描(含双路 / 单路排序原理)
java·mysql·优化·存储·by·order·filesort
AI砖家8 小时前
安全进入 Agent Loop:2027 年 Coding Agent 的决胜点
数据库·安全·codex·vibecoding
wangqiaowq9 小时前
SQL server C盘空间占满的处理
数据库·sql
文人sec9 小时前
SQL基础入门笔记 | 从零基础到掌握核心查询语句
数据库·笔记·sql
数字新视界9 小时前
机房动环监控提升运维效率
大数据·服务器·数据库·动环监控系统·动力与环境监控系统
SelectDB技术团队9 小时前
冷热分层从建到验:Storage Policy 创建、表级与分区级绑定、SHOW TABLETS 验证的完整命令
大数据·数据库·elasticsearch·搜索引擎·数据分析·apache doris·冷热分层