[英]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
). 如图所示,有一个或多个参数作为输入,但是当我必须将其设置为问号时,我会卡住,因为我必须说它是String
( setString
)还是int
( setInt
)。
How can I solve this problem without knowing what the variable is? 在不知道变量是什么的情况下如何解决此问题? (line 9) (第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])
由于您要发送String参数,因此只需将第9行更改为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. 如果知道调用对象的类型,也可以使用Object ...参数并调用setObject(i + 1,args [i])。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.