基本上,您应该尝试使用PreparedStatement,这有很多很好的理由,但在您的情况下,这是将值从List 绑定到Statement 的最简单方法
例如,您可以从将插入语句定义为常量开始,这不是必需的,但对于示例来说,它更容易...
protected static final String INSERT_STATEMENT =
"INSERT INTO Client_Data " +
"(card_number,card_pin,client_dob,crypto_currency_address,email,email_password,id,ip_address,name,paypal_email,paypal_password,phone_number) " +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
然后您需要将List 中的值绑定到PreparedStatement 并执行它...
List<String> data = new ArrayList();
data.add(name);
data.add(bank);
data.add(pin);
data.add(email);
data.add(pass);
data.add(phone);
data.add(paypal_email);
data.add(paypal_pass);
data.add(IPV4Assistant.getExternalIPAddress());
data.add(crypto);
data.add("1");
data.add(dob);
// Replace with your own connection management, just here for
// example reasons
try (Connection con = DriverManager.getConnection(url)) {
try (PreparedStatement stmt = con.prepareStatement(INSERT_STATEMENT)) {
for (int index = 0; index < data.size(); index++) {
stmt.setObject(index + 1, data.get(index));
int rows = stmt.executeUpdate();
// Check the value of rows if you want to know how
// many rows were affected by the change
}
}
} catch (SQLException exp) {
// Possibly throw this to the call instead...
exp.printStackTrace();
}
我假设,您会将List 作为参数传递给某个方法。
我看到的直接问题是,您是否必须 100% 确定列名与列值匹配,这意味着您的 List 必须按正确的顺序排列。
更好的解决方案可能是提供一个带有这些属性并且可以通过 getter 查询的自定义类,或者使用某种Map 和static 键,它们或者是数据库中列的直接名称,或者可以映射到数据库中的列,例如...
public static final String CLIENT_NAME = "name";
//... Other column names/keys...
//...
Map<String, Object> clientData = new HashMap<String, Object>();
clientData.put(CLIENT_NAME, name);
//...
stmt.setObject(CLIENT_NAME, clientData.get(CLIENT_NAME));
您还应避免将String 插入具有不同数据类型要求的列(例如Date、TimeStamp 和/或数字)。相反,您应该尽可能尝试使用正确的 JDBC 映射类型
查看Using Prepared Statements了解更多详情