我的数据库中有一个 table ,它有 2 列:
MyTable
Column1 | Column2 |
---|
在我的代码中,我有 2 个字符串 arrays (strArr
, compareArr
) 和一个具有 2 个属性引用 MyTable
的模型来保留 values。
class Model()
int col1;
String col2;
constructors; getter; setter;
然后,我的 strArr
和 compareArr
有一些 values:
strArr = {"One", "Two", "Five"};
compareArr = {"One", "Two", "Three", "Four", "Five"};
我想将 strArr
value 放入我的 Model
中,其中 col2.setCol2(strArr(i))
等于 compareArr(j)
。 col1
的 value 在循环期间是不可更改的。
这是我尝试过的代码:
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();
}
}
问题是我只能将第一个模型插入数据库,而其余的则失败。
回答1
您的数据库代码看起来不错,但我会使用 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);
}
}