eclipse的增删改查
时间: 2023-11-08 13:00:36 浏览: 113
增删改查
在eclipse中编写增删改查操作需要先连接到数据库,然后根据需要编写相应的SQL语句执行操作。下面是一个示例代码,展示了在eclipse中如何编写增删改查:
1. 增加数据:
```java
Connection conn = DBHelper.getConn();
String sql = "INSERT INTO table_name (column1, column2, ...) VALUES (?, ?, ...)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value1);
ps.setString(2, value2);
// 设置其他参数...
int result = ps.executeUpdate();
if (result > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失败");
}
DBHelper.close(null, ps, conn);
```
2. 删除数据:
```java
Connection conn = DBHelper.getConn();
String sql = "DELETE FROM table_name WHERE condition";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, condition);
// 设置其他参数...
int result = ps.executeUpdate();
if (result > 0) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
DBHelper.close(null, ps, conn);
```
3. 修改数据:
```java
Connection conn = DBHelper.getConn();
String sql = "UPDATE table_name SET column1 = ?, column2 = ... WHERE condition";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value1);
ps.setString(2, value2);
// 设置其他参数...
int result = ps.executeUpdate();
if (result > 0) {
System.out.println("修改成功");
} else {
System.out.println("修改失败");
}
DBHelper.close(null, ps, conn);
```
4. 查询数据:
```java
Connection conn = DBHelper.getConn();
String sql = "SELECT * FROM table_name WHERE condition";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, condition);
// 设置其他参数...
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// 处理查询结果...
}
DBHelper.close(rs, ps, conn);
```
阅读全文