I am unable to store the ResultSet
in an object array. I want to store it in an Object array and return it, how do I do this?
import java.sql.*;
public class TestSQLwithFunction {
private static Object[] returnObjectArray() {
String connnectionURL = "jdbc:sqlserver://localhost\\FAISAL-
FAS:1433;username=sa;password=password";
Object ob[] = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(connnectionURL);
ResultSet rs = conn.getMetaData().getSchemas();
while(rs.next()) {
ob = (Object[]) rs.getObject(1);
}
}
catch(Exception e){
e.printStackTrace();
}
return ob;
}
public static void main (String[] args) {
Object[] checkrs = returnObjectArray();
for(int i = 0; i <= checkrs.length; i++){
System.out.println(checkrs);
}
}
}
I get this exception:
java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object; at TestSQLwithFunction.returnObjectArray(TestSQLwithFunction.java:13) at TestSQLwithFunction.main(TestSQLwithFunction.java:24) Exception in thread "main" java.lang.NullPointerException at TestSQLwithFunction.main(TestSQLwithFunction.java:25)
You can use object array but you can use collection API also.
Try this:
private static ArrayList returnObjectArray()throws Exception {
String connnectionURL = "jdbc:sqlserver://localhost\\FAISAL-FAS:1433;username=sa;password=password";
ArrayList<Object> data = new ArrayList();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(connnectionURL);
ResultSet rs = conn.getMetaData().getSchemas();
while(rs.next()) {
data.add(rs.getObject(1));
}
}
catch(Exception e){
e.printStackTrace();
}
return data;
}
public static void main (String[] args) {
for(Object checkers: returnObjectArray()){
System.out.println(checkers);
}
}
I used ArrayList
. You can make this more flexible if you want, Using key-value pair. To do this you can use HashMap
, HashTable
or you can create your own custom one.
If you want custom one:
Pair
class add two variable for key and value.Pair(String key, Object o){//..}
returnObjectArray
initialize ArrayList<Pair> data = new ArrayList();
data.add(new Pair("column name", rs.getObject(1)))