Java连接MySQL实现数据库数据删除
时间: 2023-07-20 18:19:36 浏览: 106
好的,下面是Java连接MySQL实现数据库数据删除的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DeleteDataExample {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
// SQL语句
String sql = "DELETE FROM student WHERE id = 1";
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
Connection conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行SQL语句
int rows = stmt.executeUpdate(sql);
// 输出删除的行数
System.out.println("删除了 " + rows + " 行数据");
// 关闭Statement对象和数据库连接
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
代码中,我们首先定义了数据库连接信息和要执行的SQL语句,然后加载了MySQL数据库驱动,建立数据库连接,创建Statement对象,执行SQL语句,输出删除的行数,最后关闭Statement对象和数据库连接。需要注意的是,在实际使用时,应该使用PreparedStatement代替Statement,以提高安全性和性能。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)