我在这里有一些代码来获取序列的下一个值,但它每次都会在结果上添加记录总数。
我只是在学习准备好的陈述,我认为这是小事,也许rset.next()应该是别的什么?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
任何帮助表示感谢。
答案 0 :(得分:1)
我认为您不需要拨打pstmt.executeUpdate();
如ResultSet doc中所述,函数insertRow将该行存储在数据集AND中的数据库中。
以下代码显示了添加新行所需的所有内容:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
答案 1 :(得分:0)
为什么不迭代使用而不是if。像这样的东西
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
答案 2 :(得分:0)
你不应该这样做吗?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
实际上,似乎你将一个稍微伪造的字符串传递给SQL查询,这可能是默认为最大索引(不是100%肯定)。然后rs.next()只是增加它。