preparedStatement对象的execute()、executeUpdate()、executeQuery()

看过的东西忘得太快,即便记住,真正用上了才发现记的东西模棱两可。
今天用jdbc写了一段SQL语句,用PreparedStatement对象来插入对象,用pstmt.execute()的执行结果来判断数据是否插入成功:

pstmt = conn.prepareStatement("insert into columninfo(columntitle,reid,topid) values(?,?,?)");
pstmt.setString(1, column.getColumntitle());
pstmt.setInt(2, column.getReid());
pstmt.setInt(3, column.getTopid());
return pstmt.execute();

测试的时候发现,数据明明插入成功,但是execute()的返回却是false :cry: ,晕了。
网上查了API才发现,对execute()返回的true、false的理解真是想当然了~ 8)

public ResultSet executeQuery() throws SQLException
返回一个不为空的结果集

public int executeUpdate() throws SQLException
返回:1、返回INSERT、UPDATE或者DELETE语句执行后的更新行数;
2、返回0表示SQL语句没有执行成功。

public boolean execute() throws SQLException
返回:true表示SQL语句执行的结果返回ResultSet对象;
false表示SQL语句执行结果返回的是更新行数或者没有返回。


参考网址:
[url]http://download.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html[/url]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个PreparedStatement对象可以执行不同的SQL语句,只需要在创建PreparedStatement对象时,传入不同的SQL语句即可。具体步骤如下: 1. 创建Connection对象,连接到数据库。 2. 使用Connection对象的prepareStatement方法创建一个PreparedStatement对象,该对象表示预编译的SQL语句。 3. 设置PreparedStatement对象中占位符对应的参数值。 4. 执行SQL语句,使用PreparedStatement对象executeexecuteQueryexecuteUpdate方法,根据SQL语句的类型选择相应的方法。 5. 重复步骤2-4,使用不同的SQL语句,执行不同的操作。 以下是一个示例代码: ``` // 创建Connection对象 Connection conn = DriverManager.getConnection(url, username, password); // 创建PreparedStatement对象,并执行第一个SQL语句 PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE name = ?"); pstmt.setString(1, "Tom"); ResultSet rs = pstmt.executeQuery(); // 执行第二个SQL语句 pstmt = conn.prepareStatement("INSERT INTO users(name, age) VALUES(?, ?)"); pstmt.setString(1, "Jerry"); pstmt.setInt(2, 20); int rows = pstmt.executeUpdate(); // 关闭资源 rs.close(); pstmt.close(); conn.close(); ``` 在上面的代码中,首先创建了一个Connection对象,然后使用该Connection对象的prepareStatement方法创建了一个PreparedStatement对象,并执行了第一个SQL语句。接下来,使用同一个PreparedStatement对象,执行了第二个SQL语句。最后,关闭了ResultSet、PreparedStatement和Connection对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值