简体   繁体   中英

prepared statement with unknow arguments

I'm trying to create a function in which I can connect to a database and select some results. I want to do that with a prepared statement, but without knowing what type of arguments are given.

Lets say this is my test data

int id = 5;
String name = "John Doe";

then I want to call my function like this:

read("SELECT * FROM users WHERE id=?", id);

or

read("SELECT * FROM users WHERE id=? AND name=?",id,name);

As shown there is one or more argument which I get as input, but when I have to set it to a questionmark I get stuck because I have to say if it is a String ( setString ) or int ( setInt ).

How can I solve this problem without knowing what the variable is? (line 9)

1 public void read(String query, String... args){
2   try{
3       
4       Connection con = DriverManager.getConnection(databaseURL, username, password);
5       
6       PreparedStatement pstmt = con.prepareStatement(query);
7       for(int i = 0; i < args.length;i++){
8           //What do I put here?
9           pstmt.setValue(i,args[i]);
10      }


        String select = "use datapersistentie;";
        pstmt.executeQuery(select);

        ResultSet rs = pstmt.executeQuery(query); 

        while (rs.next()) {   
          // do something with the result
        }

        stmt.close();
        con.close();
    } catch (Exception e){
        System.out.println(e);
    }
}

Since you are sending in String arguments, you can just change line 9 to setString(i+1,args[i])

You could also use an Object... argument and call setObject(i+1,args[i]) if you know the types where you are calling it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM