using SetString in a for loop
I'm having a problem using setString
in for loop.
I have this line to insert into a table in my database
12.S777.V77.D88.wagon/1.Train/889
and 777 represent the number of passengers in second class.The problem is that the number of passenger is variable and can take to 3 cases ,like this example:
12.F123.S777.V77.wagon/1.Train/889
code
String rs="insert into ligne1(date,immatr,number_passenger,version,wagon,train) VALUES(?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(rs);
ps.setString(1, message[0]);
ps.setString(2, message[1]);
ps.setString(3, message[2]);
int b=0;
for(b=4;b<chaine.length-1;b++){
ps.setString(b,melement[b]);
}
//I'm stuck here ! :(
ps.setString(开发者_JAVA百科5, message[3]);
ps.setString(6, message[4]);
ps.executeUpdate();
It looks like you have an input format with a variable number of fields. In that case, splitting the string at the .
is not enough, you'll have to parse the data.
I'd implement a simple value holder class for a wagon and some logic to create an instance based on an input string. Like:
public class Ligne1 {
private String date;
private int seatsInFirstClass;
private int seatsInSecondClass;
// ...
public Ligne1(String data) {
String values[] = data.split("\.");
for (String value:values) {
if (value.startsWith("F")) {
setSeatsInFirstClass(value);
} else if (value.startsWith("wagon")) {
setWagon(value);
}
// ...
}
}
private void setSeatsInFirstClass(String value) {
seatsInFirstClass = Integer.parseInt(value.substring(1));
}
public int getSeatsInFirstClass() {
return seatsInFirstClass;
}
// if we need the total
public int getNumberOfPassengers() {
return seatsInFirstClass + seatsInSecondClass;
}
// ...
}
Finally you use an instance of Ligne1
and its getter methods to set the values on the prepared statement.
(Note: the code only gives a hint to the solution I'd choose, it's incomplete and does not handle errors in the source data)
精彩评论