使用Java的Postgresql:插入后查询未产生任何结果 [英] Postgresql with java: query produced no result after insert

查看:144
本文介绍了使用Java的Postgresql:插入后查询未产生任何结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小程序来管理我的视频收藏.

I write a little program to admin my video collection.

/*
insert new data set into the table
*/
int next = 0;
rs = st.executeQuery("Select max(category_id) from category;");
if (rs.next()) {
    next = rs.getInt(1) + 1;
    System.out.println(next);
}
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
rs = st.executeQuery(query);
//on this place is the exception thrown
// this will not execute anymore
rs = st.executeQuery("DELETE FROM category WHERE name = 'Mystics';"); 

程序可以在表上进行选择,进行联接但要插入麻烦. 我尝试在表中插入一些新数据(请参见Java代码).在第二次测试后,输出显示出已插入数据.但是在插入之后,抛出了异常. 1& 2是昨天和今天的测试. (3)已插入但尚未选择.

The program can select on tables, make joins but insert make trouble. I try to insert some new data in my table (see Java-code). After the second test the output show me that the data was inserted. But after Insert was an exception thrown. 1 & 2 are the tests from yesterday and today. (3) was inserted but not selected yet.

1   Mystics 2015-07-05
2   Mystics 2015-07-06
3
org.postgresql.util.PSQLException: query produced no result.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:287)
at postgre_java.Zetcode.main(Zetcode.java:55)

您对我有什么建议吗?

推荐答案

请勿使用读取语句来操作数据! 如果要插入,更新,删除db use中的数据

Do not manipulate data with read statements! If you want to insert, update, delete data in db use

Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);

executeQuery返回结果集,但是INSERT,UPDATE,DELETE可以返回的全部是受影响的行数,而这正是executeUpdate返回的结果.

executeQuery returns resultset, but all that INSERT, UPDATE, DELETE can return is number of affected rows and that is what executeUpdate is returning.

并且永远不要,永远不要* 100在SQL中使用字符串连接使用Prepared语句!

And never, never, never*100 use string concatenation in SQL use Prepared statements!

这篇关于使用Java的Postgresql:插入后查询未产生任何结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆