Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to return a resultset as an array?

 
tien liu
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone tell me how to turn the result below into an array of type String? Thanks for your help.
public String getBankandColor()
{
String record = " ";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("JDBC DBC:ITSCONNECT", "xxx", "xxxx");
CallableStatement cstmt = connection.prepareCall("{call getX}");
System.out.println("before exec getX");
resultSet = cstmt.executeQuery();
while(resultSet.next())
{

record = record + resultSet.getString("c1") + " " + resultSet.getString("c2");
System.out.println("record = " + record);
}
}
catch(ClassNotFoundException e)
{
e.getMessage();
}
catch(SQLException e)
{
e.getMessage();
}
System.out.println("return record = " + record);
return record;
} // end of getBankandColor
 
Denise Hum
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can add your results to an ArrayList, then call toArray() on it which will return an Array of Objects which you can then cast into Strings.
 
tien liu
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your helpful answer. How to cast records.toArray() into String?
ArrayList records = new ArrayList();

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("JDBC DBC:xxx", "xxx", "xxx");

CallableStatement cstmt = connection.prepareCall("{call getBankandColor}");
System.out.println("before exec getBankandColor");
resultSet = cstmt.executeQuery();

while(resultSet.next())
{
records.add(resultSet.getString("bank_short_n") + " " + resultSet.getString("zone_color_c"));
records.toArray();


}
 
Greg Charles
Sheriff
Posts: 3002
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, move the toArray() call outside the loop. The idea is, you add all your results to an ArrayList, which is basically just an Array that can grow when it needs to, then convert it to an real array for easier access. The cast is just (String []).
String [] allRecords = (String [])records.toArray();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic