我正在使用 Oracle Database 10g、java 并尝试使用 ResultSet 插入新行。
我有 ResultSet 对象,它是可更新的且方向不敏感,这意味着您可以沿任何方向遍历。
当我使用 moveToInsertRow、insertRow 和 setter 方法在 ResultSet 中插入行时,该行被插入到数据库中,但在遍历 ResultSet 时,我无法查看新插入的行
谁能帮帮我。
我的代码是:
import java.sql.*;
import java.io.*;
import java.util.Date;
public class TestResultSet{
public static void main(String...args){
try{
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "system", "admin");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("Select EnrNo, Name, Gender, DOB From Student");
int i;
while(rs.next()){
for(i = 1; i < 5; i++)
System.out.print(rs.getString(i) + ", ");
System.out.println();
}
//Inserting New Row
rs.moveToInsertRow();
rs.updateLong(1, 117020365276L);
rs.updateString(2, "Ashfaq");
rs.updateInt(3, 1);
Date d = new Date();
rs.updateDate(4, new java.sql.Date(d.getYear(), d.getMonth(), d.getDay()));
rs.insertRow();
//New Row Insertion ends here
rs.first(); //Moving to first row
do{
for(i = 1; i < 5; i++) //Index starts from 1, not from 0
System.out.print(rs.getString(i) + ", ");
System.out.println();
}while(rs.next());
}
catch(SQLException ex){ ex.printStackTrace(); }
catch(Exception ex){ ex.printStackTrace(); }
}
}
/*
Student Table Schema
EnrNo Numeric(12) Primary Key
Name varchar2(25);
Gender Numeric(1);
DOB date
*/
最佳答案
问题在于新行已添加到数据库中,而不是添加到从数据库恢复的当前行。因此,为了识别新行,您必须再次读取表。它可能效率低下(因为这取决于查询的行数和复杂程度),但这就是它的工作原理。
知道了这一点,你的代码应该是这样的:
ResultSet rs = stmt.executeQuery("Select EnrNo, Name, Gender, DOB From Student");
int i;
while(rs.next()) {
for(i = 1; i < 5; i++)
System.out.print(rs.getString(i) + ", ");
System.out.println();
}
//Inserting New Row
rs.moveToInsertRow();
rs.updateLong(1, 117020365276L);
rs.updateString(2, "Ashfaq");
rs.updateInt(3, 1);
Date d = new Date();
rs.updateDate(4, new java.sql.Date(d.getYear(), d.getMonth(), d.getDay()));
rs.insertRow();
//New Row Insertion ends here
//Moving to first row of the current recovered resultset
//thus not working as expected
//rs.first();
//close the resultset
rs.close();
//retrieve the rows from database again
rs = stmt.executeQuery("Select EnrNo, Name, Gender, DOB From Student");
do{
for(i = 1; i < 5; i++) //Index starts from 1, not from 0
System.out.print(rs.getString(i) + ", ");
System.out.println();
} while(rs.next());
关于java - 结果集不包含新插入的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16946275/