I have below class file. If I try to insert values from Vector to database, then it will display below error. I want to use Vector in this case and looking how to resolve this issue.
error : The method setString(int, String) in the type PreparedStatement is not applicable for the arguments (int, Object)
below is the class code:
public class ReadExcelFile {
public static void main(String[] args) {
String fileName = "C:\\excelFile.xls";
Vector dataHolder = ReadCSV(fileName);
printCellDataToConsole(dataHolder);
}
public static Vector ReadCSV(String fileName) {
Vector cellVectorHolder = new Vector();
try {
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector = new Vector();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreVector.addElement(myCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
} catch (Exception e) {
e.printStackTrace();
}
return cellVectorHolder;
}
public static void printCellDataToConsole(Vector dataHolder) {
for (int i = 0; i < dataHolder.size(); i++) {
Vector cellStoreVector = (Vector) dataHolder.elementAt(i);
// System.out.println(cellStoreVector);
for (int j = 0; j < cellStoreVector.size(); j++) {
HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j);
String stringCellValue = myCell.toString();
System.out.print(stringCellValue + "\t\t");
}
System.out.println();
}
}
}
//below is the database query
String sql = "INSERT INTO table_name(EMP_ID,FNAME, LNAME, CATEGORY, DEPARTMENT, Title, REASON, Manager, sDate, eDate, ID) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement pst1 = conn.prepareStatement(sql);
pst1.setString(1, cellStoreVector.get(0));
pst1.setString(2, cellStoreVector.get(1));
pst1.setString(3, cellStoreVector.get(2));
pst1.setString(4, cellStoreVector.get(3));
pst1.setString(5, cellStoreVector.get(4));
pst1.setString(6, cellStoreVector.get(5));
pst1.setString(7, cellStoreVector.get(6));
pst1.setString(8, cellStoreVector.get(7));
pst1.setString(9, cellStoreVector.get(8));
pst1.setString(10, cellStoreVector.get(9));
pst1.setString(11, "555"); //Hardcoded for testing.
pst1.execute();
Your
Vectoris defined to holdObjects.The
Vector#getwill return anObject.The
PreparedStatement#setStringmethod is expecting aString, this is a simple type mismatch issue.You can declare you
Vectorso that it only containsString……But I don’t think you can from your example…
You can cast the value in the
Vectorto aStringBut this is dangerous as you won’t find out that the
Vectordoesn’t contain aStringelement until run-timeOr you can let the
PreparedStatementhandle it…