String query = "select email from emp_select";
Statement stmt;
try {
DB db=new DB();
db.connect();
stmt = (Statement) db.conn.createStatement(); // DB is connected here
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print(", ");
}
System.out.println("");
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
name[i]=columnValue;
System.out.println(name[i]); //Everything executes well till here
}
}
stmt.close();
} catch(Exception ex) {}
for (int i = 1; i < name.length; i++) {
System.out.println(name[i]); // why it gives null value here ?
}
答案 0 :(得分:1)
我想知道你真正想要的是什么:
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
name[i]=columnValue;
System.out.println(name[i]); //Everything executes well till here
}
}
这里发生的事情是,while循环开始,现在for循环开始执行,现在在for循环中你给name数组的所有元素赋予相同的值,即rs.getString(i),但你的查询只返回一个您的rs的列,即电子邮件(但您在for循环中编码类似于名称[2] = rs.getString(2),name [3] = rs.getString(3),但这里除了rs之外没有其他内容。的getString(1))。看起来你应该做的就是这个,这可能会给你预期的结果
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print(", ");
if (rs.next()) // hope this works, not sure (but it does works for me at the click of a button, when used through Swing Events)
{
String columnValue = rs.getString(1);// Since only one thing is being returned by your rs object.
name[i]=columnValue;
System.out.println(name[i]); //Everything executes well till here
}
}
希望这可以解决。
此致
答案 1 :(得分:0)
好吧,让我通过这个版本的代码对此进行改写:
String query = "select email from emp_select";
Statement stmt;
try {
DB db=new DB();
db.connect();
stmt = (Statement) db.conn.createStatement(); // DB is connected here
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
List<String[]> names = new ArrayList<String[]>();
String[] name=null; //assuming here you have only Varchar cols
while (rs.next()) {
name = new String[numberOfColumns];
for (int i = 0; i <= numberOfColumns; i++)
{
name[i]=rs.getString(i);
}
names.add(name);
}
stmt.close();
} catch(Exception ex) {
ex.printStackTrace();
}
for(String[] colResults : names)
{
for (int i = 0; i < colResults.length; i++) {
System.out.println(colResults[i]);
}
}
答案 2 :(得分:0)
我想这对于名称数组的每个元素都不是“赋予空”。它可能是null,因为您的名称数组中的元素多于结果集中的列,或者因为结果集的最后一行实际上包含空值(除了最后一行之外,所有行都在抛出数组)。
附注: