如何使用java同时插入和排序数据

问题描述 投票:-2回答:1

这是我编写的示例代码:

String sql =" INSERT INTO "+tablename+" (id,timestamp,type,current_num_workers,target_num_workers) 
VALUES (?,?,?,?,?)";
PreparedStatement pstmt=con.prepareStatement(sql);

System.out.println("Fetching records in ascending order...");
String se="SELECT * FROM " + tablename + " ORDER BY type ASC";
PreparedStatement pstmt=con.prepareStatement(sql);

pstmt.setString(1, id); 
pstmt.setString(2, timestamp); 
pstmt.setString(3, type); 
pstmt.setString(4, current_num_workers); 
pstmt.setString(5, target_num_workers);
pstmt.executeUpdate();
pstmt.executeUpdate();

这是我面临的例外:

Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: A result set was 
generated for update.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:226)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement
(SQLServerPreparedStatement.java:592)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute
(SQLServerPreparedStatement.java:508)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:243)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:218)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate
(SQLServerPreparedStatement.java:461)

[帮助我解决此问题,并在同一位置整理并插入详细信息。

java sql sql-server jdbc
1个回答
0
投票

尝试这样的事情

String sql =" INSERT INTO "+tablename+" (id,timestamp,type,current_num_workers,target_num_workers) 
VALUES (?,?,?,?,?)";
PreparedStatement pstmtInsert=con.prepareStatement(sql);

System.out.println("Fetching records in ascending order...");
String se="SELECT * FROM " + tablename + " ORDER BY type ASC";
PreparedStatement pstmtSelect=con.prepareStatement(se);
Resultset rs=pstmtSelect.executeQuery();
while(rs.next()){
    pstmtInsert.setString(1, rs.getString("id")); 
    pstmtInsert.setString(2, rs.getString("timestamp")); 
    pstmtInsert.setString(3, rs.getString("type")); 
    pstmtInsert.setString(4, rs.getString("current_num_workers")); 
    pstmtInsert.setString(5, rs.getString("target_num_workers"));
    pstmtInsert.executeUpdate();
}
© www.soinside.com 2019 - 2024. All rights reserved.