关于 PreparedStatement 返回值的问题

来源:互联网 发布:大闹天宫进阶数据 编辑:程序博客网 时间:2024/05/21 00:53

今天在学习 JDBC 的 CRUD 时发现这样一个平日里不注意的问题:



package com.fengshun.dao.impl;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.fengshun.dao.PersonDao;import com.fengshun.entity.Person;/** * jdbc 方式的实现 *  * @author lining * */@Repositorypublic class JdbcPersonDao implements PersonDao {@Autowiredprivate DataSource dataSource;@Overridepublic int addPerson(Person p) {final String ADD_PERSON = "insert into person (name,age,address) values (?,?,?)";int result = 0;Connection conn = null;PreparedStatement stmt = null;try {conn = dataSource.getConnection();stmt = conn.prepareCall(ADD_PERSON);stmt.setString(1, p.getName());stmt.setInt(2, p.getAge());stmt.setString(3, p.getAddress());boolean executeResult = stmt.execute();System.out.println(executeResult);result = executeResult ? 1 : 0;} catch (SQLException e) {e.printStackTrace();} finally {try {if (stmt != null) {stmt.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}return result;}@Overridepublic Person getPerson(int id) {// TODO Auto-generated method stubreturn null;}}


上述代码中,对于 stmt.execute()方法的返回值是 false,但是数据已经正确入库,后经查找:


stmt.execute()方法返回值如果为 true,表示为 resultSet 等结果集,而如果为 false,则表示是一般的执行结果等,非更新失败;



0 0
原创粉丝点击