我已经在我的项目中创建了一个数据库连接类,以便在项目中的所有类之间创建和共享数据库实例。
使用以下代码获得的数据库连接
void createConnection(){
try{
connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "");
System.out.println("Connected");
}catch(Exception e) {
System.out.println("Connection Failed");
System.out.println(e);
}
}
然后,我创建了一个使用预准备语句向数据库插入值的方法,如下所示
public boolean execAction(String query){
try {
pstatement = (PreparedStatement) connection.prepareStatement(query);
pstatement.execute(query);
System.out.println("Values inserted");
return true;
} catch (SQLException ex) {
Logger.getLogger(databaseHandler.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Values insertion failed");
return false;
} finally {
}
我想要找到一种方法来将准备好的语句变量值传递给这个方法。
发布于 2017-04-01 16:09:40
我的建议是:首先想一想你需要这个方法做什么。它只需要接受一个值,还是多个值?参数类型是否相同?
一旦你得到了它,决定什么数据结构最能代表这一点。由于PreparedStatement通过索引引用参数,因此如果您需要很多值,则可能需要某种类型的列表。如果每个条目也需要一个类型,那么您可能需要创建一个数据类来将该类型和值保存在一个位置。
由于这看起来像是一个编程任务,所以我不会为您编写代码,但这将使我可以从以下内容开始:
public class DatabaseHandler {
public boolean execAction(String query, List<PreparedStatementArgument> arguments){
// code here
}
}
class PreparedStatementArgument {
private final PreparedStatementArgumentType type;
private final Object value;
// Constructor, getters
}
enum PreparedStatementArgumentType {
INT, STRING; //etc
}
您还可以考虑对PreparedStatementArguments使用多态性,这取决于您为此所做的准备有多复杂。
如果这不是编程赋值,请注意像这样的方法的问题是它无法验证其给定的参数是否与SQL匹配-这使得它更难发现是否存在不匹配,并且很可能使您的应用程序在长期运行中更容易出错。
https://stackoverflow.com/questions/43154091
复制相似问题