JDBC(三)——使用Statement接口对数据库实现增删改操作(3)

前面说到了使用Statement接口对数据库进行增加数据操作;

现在我们来看一下修改操作和删除操作;

其实基本原理是一样的,就是sql语句有点不一样;

1.修改操作;

我们新建一个update_sql类:

package Month01.Day08.Demo02;

import java.sql.Connection;
import java.sql.Statement;

import Month01.Day08.DbUtil.DbUtil;
import Month01.Day08.Model.Book;

public class update_sql {

	private static DbUtil dbUtil = new DbUtil();

	private static int updateBook(Book book) throws Exception {
		// 连接数据库
		Connection con = dbUtil.getCon();
		// 获取Statement接口
		Statement stmt = con.createStatement();
		// 写sql语句
		String sql = "update t_book set bookName='" + book.getBookName() + "',price=" + book.getPrice() + ",author='"
				+ book.getAuthor() + "',bookTypeId=" + book.getBookTypeId() + " where id=" + book.getId() + "";
		// 执行sql语句
		int result = stmt.executeUpdate(sql);
		// 关闭数据库连接
		dbUtil.close(stmt, con);
		return result;
	}

	public static void main(String[] args) throws Exception {
		Book book = new Book(5, "Web设计", 65, "大奶牛", 2);
		int result = updateBook(book);
		if (result == 1) {
			System.out.println("数据修改成功!");
		} else {
			System.out.println("数据修改失败!");
		}
	}
}

将表t_book中ID为5的数据修改如上;

原先表中内容为:

程序执行修改之后为:

 

可以看到数据修改成功!

 

 2.删除操作;

我们新建一个delete_sql类:

package Month01.Day08.Demo02;

import java.sql.Connection;
import java.sql.Statement;

import Month01.Day08.DbUtil.DbUtil;

public class delete_sql {

	private static DbUtil dbUtil = new DbUtil();

	private static int deleteBook(int id) throws Exception {
		// 连接数据库
		Connection con = dbUtil.getCon();
		// 获取Statement接口
		Statement stmt = con.createStatement();
		// sql语句
		String sql = "delete from t_book where id=" + id + "";
		// 执行sql语句
		int result = stmt.executeUpdate(sql);
		// 关闭数据库连接
		dbUtil.close(stmt, con);
		return result;
	}

	public static void main(String[] args) throws Exception {
		int result = deleteBook(6);
		if (result == 1) {
			System.out.println("数据删除成功!");
		} else {
			System.out.println("数据删除失败!");
		}
	}
}

 将表中ID为6的那条数据删除掉;

原表中数据为:

程序执行修改之后为:

可以明显看到ID为6的那条数据已经删除成功! 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值