Postgresql with java:insert后查询未生成结果
我写了一个小程序来管理我的视频收藏Postgresql with java:insert后查询未生成结果,java,postgresql,jdbc,Java,Postgresql,Jdbc,我写了一个小程序来管理我的视频收藏 /* 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 categor
/*
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代码)。第二次测试后,输出显示数据已插入。但Insert之后抛出了一个异常。
1和2是昨天和今天的测试。(3) 已插入,但尚未选择
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)
您有什么建议吗?在Java中,您使用
executeQuery
作为SELECT
语句或其他返回内容的语句。如果要执行INSERT
、UPDATE
或DELETE
而不返回任何内容,应使用executeUpdate()
请勿使用read语句操作数据!
如果要在db use中插入、更新、删除数据
Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);
executeQuery返回resultset,但INSERT、UPDATE、DELETE可以返回的只是受影响的行数,这就是executeUpdate返回的行数
永远,永远,永远*100在SQL中使用字符串连接使用准备好的语句 就是为了这个目的
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
int noOfRows= st.executeQuery(query)
但它不会返回结果集
,而是返回可以存储到整数中的受影响行数
此外,您的非常容易受到攻击,请尝试使用来保护您的代码executeUpdate()
i thinkUse。