java中mysql的update
时间: 2023-11-30 21:43:42 浏览: 307
Java中MySQL的update可以通过JDBC实现。具体步骤如下:
1. 导入JDBC驱动包,连接MySQL数据库。
2. 创建Statement对象。
3. 编写SQL语句,使用update关键字更新表中的数据。
4. 执行SQL语句,更新数据。
5. 关闭Statement对象和数据库连接。
以下是一个Java程序示例,用于更新MySQL表中的数据:
```java
import java.sql.*;
public class UpdateExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
try {
// 1.连接数据库
conn = DriverManager.getConnection(url, user, password);
// 2.创建Statement对象
stmt = conn.createStatement();
// 3.编写SQL语句,使用update关键字更新表中的数据
String sql = "UPDATE mytable SET name='Tom' WHERE id=1";
// 4.执行SQL语句,更新数据
int rows = stmt.executeUpdate(sql);
System.out.println(rows + " rows updated.");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 5.关闭Statement对象和数据库连接
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```