java程序jdbc数据库增删改查
时间: 2024-06-16 08:02:05 浏览: 13
在Java中,使用JDBC(Java Database Connectivity)进行数据库操作,包括增删改查(CRUD),是连接和处理数据库的标准方法。以下是一些基本的步骤:
1. **连接数据库**:
- 导入`java.sql`或对应的驱动包,如`com.mysql.jdbc.Driver`。
- 使用`DriverManager.getConnection(url, username, password)`创建连接,其中url是数据库URL,username和password是数据库用户名和密码。
2. **创建Statement或PreparedStatement**:
- `Statement`用于执行SQL语句,而`PreparedStatement`更安全且性能更好,因为它可以预编译语句并支持参数化查询。
3. **插入数据(INSERT)**:
- 使用`PreparedStatement`的`setXXX()`方法设置参数,然后调用`executeUpdate()`执行插入。
```java
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, value1);
pstmt.setInt(2, value2);
int rowsInserted = pstmt.executeUpdate();
```
4. **更新数据(UPDATE)**:
- 类似于插入,但SQL可能包含条件。
```java
String sql = "UPDATE table_name SET column1 = ? WHERE condition";
pstmt.setString(1, newValue);
rowsUpdated = pstmt.executeUpdate();
```
5. **删除数据(DELETE)**:
- 删除操作也类似,但SQL中指定删除的条件。
```java
String sql = "DELETE FROM table_name WHERE condition";
pstmt.executeUpdate();
```
6. **查询数据(SELECT)**:
- 使用`Statement`或`PreparedStatement`执行查询,获取结果集(ResultSet)。
```java
String sql = "SELECT * FROM table_name WHERE condition";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
// 处理查询结果
}
```
7. **关闭资源**:
- 一定要记得关闭`Connection`, `Statement`, 和`ResultSet`,防止内存泄漏。
```java
rs.close();
stmt.close();
connection.close();
```
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)