Java JDBC: Update Database Data
To modify database data, you can use JDBC to execute SQL statements. Below is a simple example code to demonstrate how to use JDBC to modify database data.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class UpdateDataExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try {
// 创建数据库连接
Connection connection = DriverManager.getConnection(url, username, password);
// 创建Statement对象
Statement statement = connection.createStatement();
// 执行SQL语句来修改数据
String sql = "UPDATE mytable SET column1 = 'new value' WHERE id = 1";
int rowsAffected = statement.executeUpdate(sql);
// 输出受影响的行数
System.out.println("Rows affected: " + rowsAffected);
// 关闭连接
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In the above example, a database connection is first created, followed by creating a Statement object to execute the SQL statement UPDATE mytable SET column1 = ‘new value’ WHERE id = 1 to modify data. By calling the executeUpdate method, the update operation can be executed and the number of affected rows will be returned. Lastly, remember to close the connection.