记录 代码
增加数据
// 添加数据
@Test
public boolean testAdd() throws Exception {
// 加载配置文件
Properties prop = new Properties();
prop.load(new FileInputStream("src/druid.properties"));
//获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
// 获取数据库连接对象
Connection conn = dataSource.getConnection();
String sql = "insert into quange.tb_brand (brand_name, company_name, ordered, description, status) values" +
" (?,?,?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "老坛涮菜");
preparedStatement.setString(2, "老谭涮菜有限公司");
preparedStatement.setInt(3, 20);
preparedStatement.setString(4, "脚气老谭");
preparedStatement.setInt(5, 1);
// 执行mysql
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("添加数据成功");
// 关闭链接
preparedStatement.close();
conn.close();
return true;
} else {
System.out.println("添加失败!");
return false;
}
}
修改数据
// 修改数据
@Test
public void testUpdate() throws Exception {
// 加载配置文件
Properties prop = new Properties();
prop.load(new FileInputStream("src/druid.properties"));
//获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
// 获取数据库连接对象
Connection conn = dataSource.getConnection();
String sql = "update quange.tb_brand set brand_name=?,company_name=?,ordered=?,description=?,status=? where id =?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "老谭");
preparedStatement.setString(2, "老谭酸菜牛肉面");
preparedStatement.setInt(3, 30);
preparedStatement.setString(4, "牛肉面");
preparedStatement.setInt(5, 1);
preparedStatement.setInt(6, 4);
int i = preparedStatement.executeUpdate();
System.out.println(i > 0);
// 关闭链接
preparedStatement.close();
conn.close();
}
删除数据
// 删除数据
@Test
public void testDel() throws Exception {
// 加载配置文件
Properties prop = new Properties();
prop.load(new FileInputStream("src/druid.properties"));
//获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
// 获取数据库连接对象
Connection conn = dataSource.getConnection();
String sql = "delete from tb_brand where id=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1,4);
int i = preparedStatement.executeUpdate();
System.out.println(i > 0);
// 关闭链接
preparedStatement.close();
conn.close();
}
评论区