连接实验一的数据库,操作商品表,利用JdbcTemplate进行增、删、改、查操作。
时间: 2023-07-10 13:19:33 浏览: 128
JdbcTemplate方法介绍与增删改查操作实现
好的,我会根据您的要求进行操作。以下是连接实验一数据库、操作商品表并利用JdbcTemplate进行增、删、改、查操作的示例代码:
```java
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.util.List;
public class Example {
public static void main(String[] args) {
// 创建数据源,连接实验一数据库
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/experiment1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
dataSource.setUsername("root");
dataSource.setPassword("password");
// 创建JdbcTemplate对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
// 插入数据
String insertSql = "INSERT INTO goods (name, price, stock) VALUES (?, ?, ?)";
Object[] insertParams = {"商品1", 100, 10};
int insertCount = jdbcTemplate.update(insertSql, insertParams);
System.out.println("插入了" + insertCount + "条数据");
// 删除数据
String deleteSql = "DELETE FROM goods WHERE id=?";
Object[] deleteParams = {1};
int deleteCount = jdbcTemplate.update(deleteSql, deleteParams);
System.out.println("删除了" + deleteCount + "条数据");
// 修改数据
String updateSql = "UPDATE goods SET price=?, stock=? WHERE id=?";
Object[] updateParams = {200, 20, 2};
int updateCount = jdbcTemplate.update(updateSql, updateParams);
System.out.println("修改了" + updateCount + "条数据");
// 查询数据
String selectSql = "SELECT * FROM goods";
List<Goods> goodsList = jdbcTemplate.query(selectSql, (resultSet, i) -> {
Goods goods = new Goods();
goods.setId(resultSet.getInt("id"));
goods.setName(resultSet.getString("name"));
goods.setPrice(resultSet.getDouble("price"));
goods.setStock(resultSet.getInt("stock"));
return goods;
});
System.out.println("查询到了" + goodsList.size() + "条数据");
for (Goods goods : goodsList) {
System.out.println(goods);
}
}
}
class Goods {
private int id;
private String name;
private double price;
private int stock;
// 省略getter和setter方法
@Override
public String toString() {
return "Goods{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", stock=" + stock +
'}';
}
}
```
需要注意的是,上述代码中的实验一数据库连接信息和密码应该根据您的实际情况进行修改。同时,代码中的Goods类是一个简单的JavaBean,用于封装商品信息。您可以根据实际情况修改或删除该类。
阅读全文