Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java how retrieve data from database

I have code

public static String getData(String query) {
        String output = "";
        try {
            String connectionUrl = "jdbc:sqlserver://localhost:1234;databaseName=123;user=123;password=123";
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                con = DriverManager.getConnection(connectionUrl);
                String SQL = "select smth from tableName where smth";
                stmt = con.createStatement();
                rs = stmt.executeQuery(query);
                while (rs.next()) {
                    output =  (String) rs.getObject(1);
                }
                rs.close();
        }
        catch (Exception e) {

            return "ERROR while retrieving data: " + e.getMessage();
        }
        return output;
    }

It works if value is string. But if it integer? Or boolean? How to modify this method so it would be universal, no matter what type data I get I still return it as string?

like image 476
babboon Avatar asked Feb 14 '23 22:02

babboon


1 Answers

First retreive the result in ResultSet rs, then you can write the code like below.

You can check the instance of the object and than assign the value.


String str;

Object obj = (Object)rs.getObject(1);

if(obj instanceof String){
   //do you work here for string like below
     str=(String)obj;
}
else if (obj instanceof Integer){
   //do your work for Integer
}

// same you can do for other types


like image 73
Ashu Phaugat Avatar answered Feb 27 '23 09:02

Ashu Phaugat