为什么更新数据库显示成功但是实际上没有成功?

rainy14f 2003-08-19 06:11:30
原码如下:
executeUpdate的返回值是表示更新了多少条数据吧?我执行后显示r的值为1,也就是增加了一条记录。但是数据库里并没有增加。这是怎么回事?

//增加留言
public int updateTable(String name, String content ) {
int r = 0;
try {
conn = DriverManager.getConnection( connStr,"","");
Statement stmt=conn.createStatement();
r = stmt.executeUpdate("INSERT INTO comment (name, content)" +
"VALUES( '" + name + "','" + content + "')" );
}
catch( SQLException e ) {
System.err.print(" SQL Error" + e );
}
return r;
}
...全文
414 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
rainy14f 2003-08-20
  • 打赏
  • 举报
回复
我知道了! 还是commit的事。更改表里的数据后,要调用commit方法提交更改,才能更新数据库的数据。而commit只有当setAutoCommit(false)时才会起作用。而当一个conn对象建立时,默认AutoCommit是true。但是至于设置为AutoCommit时,它会在什么时候自动提交,我看了jdk help,也还没有明白。我在这里试了一下,也没有成功。哪位大侠讲解一下自动提交!

//增加留言
public int updateTable(String name, String content ) {
int r = 0;
try {
conn = DriverManager.getConnection( connStr,"","");
conn.setAutoCommit(false); //改了这里,commit设为手动
Statement stmt=conn.createStatement();
//数据库查询里用的是单引号
r = stmt.executeUpdate("INSERT INTO comment (name,content)" +
" VALUES( '" + name + "','" + content + "')" );
System.out.println( "INSERT INTO comment (name,content)" +
" VALUES( '" + name + "','" + content + "')");
conn.commit(); //提交变更
}
catch( SQLException e ) {
System.err.print(" SQL Error" + e );
}
return r;
}
csdnxw 2003-08-20
  • 打赏
  • 举报
回复
你要先看一下java编程规范,这样对你对别人都有好处。
rainy14f 2003-08-20
  • 打赏
  • 举报
回复
executeUpdate()执行成功时,返回更新记录的条数,否则返回0,所以我构造的方法返回值也用了int型。

public int executeUpdate(String sql)
throws SQLException


Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

Parameters:

sql - an SQL INSERT, UPDATE or DELETE statement or an SQL statement that returns nothing

Returns:

either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing

Throws:

SQLException - if a database access error occurs or the given SQL statement produces a ResultSet object
hocus 2003-08-19
  • 打赏
  • 举报
回复
自己构造一个返回 boolean的 update类最好
执行indsert update之类无Result返回的操作
插入了返回true,否则反之。
hocus 2003-08-19
  • 打赏
  • 举报
回复
这个返回值很可疑啊:)

stmt.executeUpdate()
返回什么,你确信是常量1么?如果不确定,你凭什么这么判断?
liuyi8903 2003-08-19
  • 打赏
  • 举报
回复
r 应该定义成ResultSet才行。你需要返回一个结果集的。
你定义成整型难道编译器不报错吗?
rainy14f 2003-08-19
  • 打赏
  • 举报
回复
to sumny(袋鼠) :
什么地方不规范,请指教!

to Wnyu(西门吹水):
明天试一下先!
Wnyu 2003-08-19
  • 打赏
  • 举报
回复
conn = DriverManager.getConnection( connStr,"","");
后加入一句
conn.AutoCommit = true;
sumny 2003-08-19
  • 打赏
  • 举报
回复
你的代码不太规范吧
along603 2003-08-19
  • 打赏
  • 举报
回复
你最后commit一下看看呀

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧