Java how to retrieve data from a database

I have a 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 the value is a string. But if it is whole? Or logical? How to change this method so that it is universal, no matter what type data I receive, I still return it as a string?

+4
source share
6 answers

First return the result to ResultSet rs, then you can write the code as shown below.

You can check an instance of an object and assign a 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 thing you can do for other types


+3
source

in this line

output =  (String) rs.getObject(1);

if string then use

output =   rs.getString(1);

if int

output =   rs.getInt(1);

oracle

+2
+1

, , String Object. , . , . . API ResultSet .

For String

rs.getString(1);

For Int

rs.getInt(1)

ResultSet

+1
 while (rs.next()) 
 {
       String[] data;
       data = new String[100];
       data[i] = rs.getString("smth");
       i = i + 1;

  }

, . .

+1
source

how about toString ()?

while (rs.next()) {
  output = rs.getObject(1).toString();
}
0
source

All Articles