executeupdate

更新时间:02-11 教程 由 冰魄 分享

在MySQL中,executeUpdate是执行更新语句的方法之一。它可用于执行INSERT、UPDATE、DELETE等SQL语句,并返回受影响行数。

使用executeUpdate方法需要创建一个Statement对象并通过它执行SQL语句。下面是一个示例代码:

import java.sql.*;public class Example {public static void main(String[] args) throws SQLException {Connection conn = null;Statement stmt = null;try {Class.forName("com.mysql.cj.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase?user=root&password=root");stmt = conn.createStatement();String sql = "UPDATE employee SET age=25 WHERE id=1";int rowsAffected = stmt.executeUpdate(sql);System.out.println("Rows affected: " + rowsAffected);} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if (stmt != null) {stmt.close();}if (conn != null) {conn.close();}}}}

在这个示例中,我们首先通过Class.forName方法加载MySQL驱动程序,并使用DriverManager.getConnection方法建立与数据库的连接。然后,我们创建一个Statement对象并将要执行的SQL语句传递给它。在执行语句后,我们使用返回的受影响行数打印一条消息。

需要注意的是,executeUpdate方法只能用于执行更新语句,不能用于执行查询语句。如果要执行查询语句,我们可以使用executeQuery方法,并返回ResultSet对象。

声明:关于《executeupdate》以上内容仅供参考,若您的权利被侵害,请联系13825271@qq.com
本文网址:http://www.25820.com/tutorial/14_2074292.html