mysql resultset用法_小谈ResultSet用法

下面是个完整的范例,注意我们在查询结束后,可以使用Statement的close()方法来释放Statement的资料库资源与JDBC资源,而后不使用连线时也使用Connection的close()来关闭连线:

DBTest.java

package onlyfun.caterpillar;

import java.sql.*;

public class DBTest ...{

public static void main(String[] args) ...{

String driver = "com.mysql.jdbc.Driver";

String url = "jdbc:mysql://localhost:3306/GUESTBOOK?" + "useUnicode=true&characterEncoding=Big5" ;

String user = "caterpillar";

String password = "123456";

Connection conn = null;

Statement stmt = null;

try ...{

Class.forName(driver);

conn = DriverManager.getConnection(URL, user, password);

stmt = conn.createStatement();

stmt.execute("INSERT INTO message VALUES(‘xxx" +

"‘, ‘xxx@mail.com‘, ‘留言吧‘, "+ "‘2007-05-15‘, ‘顶‘)");

ResultSet result = stmt.executeQuery("SELECT * FROM message");

while(result.next()) ...{

System.out.print(result.getString(1) + " ");

System.out.print(result.getString(2) + " ");

System.out.print(result.getString(3) + " ");

System.out.print(result.getString(4) + " ");

System.out.println(result.getString(5) + " ");

}

}catch(ClassNotFoundException e) ...{

System.out.println("找不到驱动程式");

e.printStackTrace();

}catch(SQLException e) ...{

e.printStackTrace();

}finally ...{

if(stmt != null) ...{

try ...{

stmt.close();

}catch(SQLException e) ...{

e.printStackTrace();

}

}

if(conn != null) ...{

try ...{

conn.close();

}catch(SQLException e) ...{

e.printStackTrace();

}

}

}

}

}

后注意的是,Connection物件预设为自动"认可"(Commit),也就是Statement执行SQL叙述完后,马上对资料库进行操作变更,如果想要对Statement要执行的SQL进行除错,可以使用setAutoCommit(false)来将自动认可取消,在执行完SQL之后,再呼叫Connection的commit()方法认可变更,使用Connection的getAutoCommit()可以测试是否设定为自动认可.

不过无论是否有无执行commit()方法,只要SQL没有错,在关闭Statement或Connection前,都会执行认可动作,对资料库进行变更.

来源:考试大-Java认证

责编:zj  评论 纠错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值