我在資料庫中有一個包含 2 列的表:
MyTable
| 第 1 列 | 第 2 列 |
|---|
在我的代碼中,我有 2 個字串陣列 ( strArr, compareArr) 和一個具有 2 個屬性參考的模型MyTable來保留值。
class Model()
int col1;
String col2;
constructors; getter; setter;
然后,我的strArr和compareArr有一些價值觀:
strArr = {"One", "Two", "Five"};
compareArr = {"One", "Two", "Three", "Four", "Five"};
我想將strArr值放入我Model的col2.setCol2(strArr(i))等于compareArr(j). 的col1值在回圈期間是不可更改的。
這是我嘗試過的代碼:
Model model = new Model();
model.setCol1(1);
for(String value : strArr)
{
for(String cmpVal : compareArr)
{
if(value.equalsIgnoreCase(cmpVal))
{
model.setCol2(cmpVal);
break;
}
}
myTableController.insertMyTable(model); // Insert function into MyTable
}
insertMyTable(model):
public void insertMyTable(Model model){
try{
String url = "jdbc:msql://localhost/TestDB";
Connection conn = DriverManager.getConnection(url,"sa","123");
String sql = "INSERT INTO MyTable VALUES (?, ?)"
PreparedStatement ps = conn.prepareStatement();
ps.setInt(1, model.getCol1);
ps.setString(2, model.getCol2);
ps.executeUpdate();
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
問題是我只能將第一個模型插入資料庫,而其余的則失敗。
uj5u.com熱心網友回復:
您的資料庫代碼看起來不錯,但我會使用 try-with-resources 塊。運行它,請確認這是否是您想要的:
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class Model {
private int col1;
private String col2;
public Model() {
}
public Model(int col1, String col2) {
this.col1 = col1;
this.col2 = col2;
}
public int getCol1() {
return this.col1;
}
public String getCol2() {
return this.col2;
}
public void setCol1(int col1) {
this.col1 = col1;
}
public void setCol2(String col2) {
this.col2 = col2;
}
public String toString() {
return String.format("%s=%d,%s=%s", "col1", col1, "col2", col2);
}
public static void main(String[] args) {
String[] strArr = { "One", "Two", "Five" };
String[] compareArr = { "One", "Two", "Three", "Four", "Five" };
List<String> common = new ArrayList<>(List.of(strArr));
common.retainAll(new ArrayList<>(List.of(compareArr)));
List<Model> models = new ArrayList<>();
for (String col2 : common) {
Model m = new Model();
m.setCol1(10);
m.setCol2(col2);
models.add(m);
}
System.out.println(models);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475624.html
下一篇:ARRAYFORMULA(VLOOKUP(QUERY(IMPORTRANGEs)))代替ARRAYFORMULA(QUERY(IMPORTRANGEs))不起作用
