java数据库增删改查mysql代码
时间: 2023-10-02 11:08:24 浏览: 59
以下是Java使用MySQL进行增删改查的代码示例:
1. 导入MySQL驱动
```
import java.sql.*;
```
2. 连接MySQL数据库
```
String url = "jdbc:mysql://localhost:3306/db_name";
String user = "username";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
```
3. 插入数据
```
String sql = "INSERT INTO table_name (column1, column2, ...) VALUES (?, ?, ...)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, value1);
statement.setString(2, value2);
// ...
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new row has been inserted.");
}
```
4. 更新数据
```
String sql = "UPDATE table_name SET column1=?, column2=?, ... WHERE id=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, newValue1);
statement.setString(2, newValue2);
// ...
statement.setInt(6, id);
int rowsUpdated = statement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("The row with id " + id + " has been updated.");
}
```
5. 删除数据
```
String sql = "DELETE FROM table_name WHERE id=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, id);
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("The row with id " + id + " has been deleted.");
}
```
6. 查询数据
```
String sql = "SELECT * FROM table_name WHERE column=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, value);
ResultSet result = statement.executeQuery();
while (result.next()) {
int id = result.getInt("id");
String column1 = result.getString("column1");
String column2 = result.getString("column2");
// ...
System.out.println("id: " + id + ", column1: " + column1 + ", column2: " + column2 + ", ...");
}
```
注意:以上代码仅为示例,实际应用中需要根据具体情况进行修改和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)