查询5
String query5 ="USE DBTwo\n" +
"DECLARE @temp_table table (column1 VARCHAR(60))\n" +
"insert into @temp_table (column1)\n" +
"select column1 from real_table (nolock)";
查询3
String query3 = "USE DBTwo\n" +
"select column1 from @temp_table";
连接;
ResultSet rs1;
Statement stmt;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.131.10;" +"databaseName=DBOne;" +"user=" + "exuser" + ";" + "password="+"userpass" + ";" + "allowMultiQueries=true" + ";";
Connection con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
获取结果集;
try {
int rowcount = stmt.executeUpdate(query5);
System.out.println(rowcount);
rs1 = stmt.executeQuery(query3);
while (rs1.next()) {
System.out.println(rs1.getString(1));
}
rs1.close();
}
catch (SQLException sqlex){
sqlex.printStackTrace();
}
Sql Exception 抛出错误;
com.microsoft.sqlserver.jdbc.SQLServerException: Must declare the table variable "@temp_table".`rowcount` return 7
所以我成功填充了@temp_table
,我没有关闭stmt
连接并尝试从中获取结果集@temp_table
。但是 SQL 说我还没有声明这个表。这怎么可能 ?
- 解决了 -
只创建一个查询;
String query5 ="USE DBTwo\n" +
"DECLARE @temp_table table (column1 VARCHAR(60))\n" +
"insert into @temp_table (column1)\n" +
"select column1 from real_table(nolock)\n" +
"select column1 from @temp_table";
获取多个结果,如下所示;
try {
boolean result = stmt.execute(query5);
while (true)
if(result){
rs1 = stmt.getResultSet();
while (rs1.next()) {
System.out.println(rs1.getString(1));
}
} else {
int updateCount = stmt.getUpdateCount();
if (updateCount == -1){
break;
}
result = stmt.getMoreResults();
}
catch (SQLException sqlex){
sqlex.printStackTrace();
}