JDBC(四)——使用PreparedStatement接口对数据库实现增删改操作(1)

上一篇博客说到我们可以用Statement接口对数据库进行增删改操作;

但是在写sql语句的时候需要拼接字符串,极其麻烦;

1.PreparedStatement接口的引入:

PreparedStatement接口是Statement接口的子接口,属于预处理操作,与直接使用Statement接口不同的是,

PreparedStatement在操作时,是先在数据库表中准备好了一条sql语句,但是此sql语句的内容暂不设定,而是之后在具体设置;

 2.使用PreparedStatement接口实现添加数据操作:

第一步:连接数据库;

private static DbUtil dbUtil=new DbUtil();

//连接数据库
Connection con=dbUtil.getCon();

第二步:写sql语句,注意此时的sql语句内容都是未知量;

// 写sql语句
String sql = "insert into t_book values(?,?,?,?,?)";

第三步:获取PreparedStatement接口;

// 获取PreparedStatement接口
PreparedStatement pstmt = con.prepareStatement(sql);

第四步:用PreparedStatement里面的方法给之前的sql里面的位置了赋具体值;

// 给未知量赋值
		pstmt.setInt(1, book.getId());
		pstmt.setString(2, book.getBookName());
		pstmt.setFloat(3, book.getPrice());
		pstmt.setString(4, book.getAuthor());
		pstmt.setInt(5, book.getBookTypeId());

第五步:执行sql语句;

// 执行sql语句
		int result = pstmt.executeUpdate();

第六步:关闭数据库连接;

// 关闭数据库连接
		dbUtil.close(pstmt, con);

注意:这里的pstmt对象的接口PreparedStatement是Statement的子接口,关闭的时候可以继承自父接口的多态操作!

以上就是使用PreparedStatement接口对数据库进行增删改操作的完整步骤;

综合起来就是:

package Month01.Day08.Demo03;

import java.sql.Connection;
import java.sql.PreparedStatement;

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

public class PreparedStatement_insert_sql {

	private static DbUtil dbUtil = new DbUtil();

	private static int addBook(Book book) throws Exception {
		// 连接数据库
		Connection con = dbUtil.getCon();
		// 写sql语句
		String sql = "insert into t_book values(?,?,?,?,?)";
		// 获取PreparedStatement接口
		PreparedStatement pstmt = con.prepareStatement(sql);
		// 给未知量赋值
		pstmt.setInt(1, book.getId());
		pstmt.setString(2, book.getBookName());
		pstmt.setFloat(3, book.getPrice());
		pstmt.setString(4, book.getAuthor());
		pstmt.setInt(5, book.getBookTypeId());
		// 执行sql语句
		int result = pstmt.executeUpdate();
		// 关闭数据库连接
		dbUtil.close(pstmt, con);
		return result;
	}

	public static void main(String[] args) throws Exception {
		Book book = new Book(6, "编程之道", 100, "亨得利", 4);
		int result = addBook(book);
		if (result == 1) {
			System.out.println("数据添加成功!");
		} else {
			System.out.println("数据添加失败!");
		}
	}
}

 原t_book表中的数据为:

程序执行之后t_book表中数据为:

可以看到数据添加成功! 

猜你喜欢

转载自blog.csdn.net/qq_37084904/article/details/86155833