我从数据库中提取数据 com.microsoft.sqlserver.jdbc.SQLServerException: The index 15 is out of range.
期间 RunTime
.
我的连接类执行如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLConnection {
private String type = "jdbc:sqlserver:";
private String url = "//thinkThisIsAnActualAddress;";
private String database = "database=SomeDatabase;";
private String user = "user=NotAUser;";
private String password = "password=NotAPass;";
private String connectionURL;
private final String query = "SELECT FIELD1, FIELD2, FIELD3, FIELD4, FIELD4, FIELD5"
+ " FIELD6, FIELD7, FIELD8, FIELD9, FIELD10, FIELD11,"
+ " FIELD12, FIELD13, FIELD14"
+ " FROM TABLE_OWNER.TABLE_FIELDS_DTL"
+ " LEFT JOIN TABLE_OWNER2.TABLE_FIELDS_DTL2"
+ " ON TABLE_OWNER.TABLE_FIELDS_DTL.SOME_FOREIGN_KEY_SK = TABLE_OWNER2.TABLE_FIELDS_DTL.SOME_FOREIGN_KEY_SK"
+ " WHERE THIS_FIELD = 'X'";
ResultSet resultSet = null;
public String getURL(){
makeString();
return connectionURL;
}
public void makeString(){
connectionURL = type + url + database + user + password;
}
public void connect(){
// Load SQL Server JDBC driver and establish connection.
System.out.print("Dialing the Matrix... ");
try (Connection connection = DriverManager.getConnection(getURL());
Statement statement = connection.createStatement();) {
// Connection message
System.out.println("You are in, Neo...");
resultSet = statement.executeQuery(query);
int i = 1;
while(resultSet.next()){
System.out.println(resultSet.getString(i) + " ");
i++;
}
} catch (SQLException e) {
System.out.println();
e.printStackTrace();
}
}
}
我明白为什么会这样 while
回路:
int i = 1;
while(resultSet.next()){
System.out.println(resultSet.getString(i) + " ");
i++;
}
我不太明白如何在没有它的情况下获取数据,因为数据库中有14个字段,以及与该查询匹配的任意行数,具体取决于日期。一个简单的“修正”就是交换线路 while(resultSet.next())
至 while(resultSet.next() && i < 14)
,这将修复异常,但无法实现我要查找的结果,即遍历与查询匹配的所有行的能力。
我错过了什么?
1条答案
按热度按时间p3rjfoxz1#
如果你想阅读每一行,你可以使用
while (rs.next())
循环,它将为每一行开火。如果对于一行,您想读取每一列,那么可以使用
.getString(col)
或者.getInt(col)
或者.getObject(col, LocalDateTime.class)
或者getwhateveryouwant方法,传递col
arg可以是基于1的索引,也可以是要获取的列的名称。如果两者都需要,那么就必须获取元数据来知道有多少列,或者,只需检查自己的查询并硬编码数字。因此,对于特定代码,如果要打印每行中的每一列:
如果查询返回4行,将打印4*14=56行文本。