Aggiornato da SQL 2000 a SQL 2005 e passato a Microsoft SQL Server 2005 JDBC Driver versione 1.2. Ho ricevuto l'errore "L'istruzione non ha restituito un risultato" durante l'esecuzione di un Insert seguito da SELECT SCOPE_IDENTITY() ". Ho risolto il problema utilizzando executeUpdate() e getGeneratedKeys invece di executeQuery. Ecco il codice prima e dopo.
Nota: la connessione utilizzata in questo esempio è java.sql.Connection non il com.microsoft.sqlserver.jdbc.SqlServerConnection
SQL 2000 codice
String dbURL = "jdbc:sqlserver" + "://" + dbServer + ":" +
dbServerPort + ";SelectedMethod=cursor;databaseName="
+ dbName + ";user=xxx;password=xxx";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
java.sql.Connection connection = DriverManager.getConnection(dbURL);
sql = "insert into Contact (name) values ('ABC'); SELECT SCOPE_IDENTITY()";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println("Id=" + id);
}
SQL 2005. codice
String dbURL = "jdbc:sqlserver" + "://" + dbServer + ":" +
dbServerPort + ";SelectedMethod=cursor;databaseName="
+ dbName + ";user=xxx;password=xxx";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
java.sql.Connection connection = DriverManager.getConnection(dbURL);
sql = "insert into Contact (name) values ('ABC'); SELECT SCOPE_IDENTITY()";
PreparedStatement ps = connection.prepareStatement(sql);
ps.executeUpdate(); // do not use execute() here otherwise you may get the error
// The statement must be executed before
// any results can be obtained on the next
// getGeneratedKeys statement.
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println("Id=" + id);
}
fonte
2010-10-01 01:28:22
Non tutti i driver consentono l'esecuzione di blocchi di istruzioni come una query. Se questo funziona in uno e non in un altro è il probabile colpevole. – Donnie
che non sarebbe molto prudente con Microsoft donnie, un select scope_identity() DEVE verificarsi prima di ogni altro inserto e su una connessione con lo stesso ID di lavoro. Ovviamente è possibile eseguire le query back to back, ma limita il modo in cui una connessione aperta può essere utilizzata dalle applicazioni. Anche il server SQL non ha problemi nell'esecuzione di più query e il driver non è a conoscenza di T-SQL, quindi non ha idea di cosa sta eseguendo. - Vainstah 0 sec fa –