我有我的代碼編寫來保存我的用戶的數據在excel文件到MySQL數據庫。當我運行它時,除日期錯誤外,一切正常。在excel文件中,日期格式是dd.MM.yyyy,而MySQL中的日期格式是yyyy-MM-dd。在我的代碼中,我應該如何轉換日期格式並將其保存到數據庫中?更改日期格式的Excel日期數據,同時保存到數據庫與Java
這些代碼:
import java.io.FileInputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelToDb {
public static void main(String [] args) {
String fileName="testing.xlsx";
Vector dataHolder=read(fileName);
saveToDatabase(dataHolder);
}
public static Vector read(String fileName) {
Vector cellVectorHolder = new Vector();
try{
FileInputStream myInput = new FileInputStream(fileName);
//POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
XSSFRow myRow = (XSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
//Vector cellStoreVector=new Vector();
List list = new ArrayList();
while(cellIter.hasNext()){
XSSFCell myCell = (XSSFCell) cellIter.next();
list.add(myCell);
}
cellVectorHolder.addElement(list);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void saveToDatabase(Vector dataHolder) {
String activityId="";
String activityName="";
String activityAllocation="";
String activityDate="";
String activityPersonInCharge="";
System.out.println(dataHolder);
for(Iterator iterator = dataHolder.iterator();iterator.hasNext();) {
List list = (List) iterator.next();
activityId= list.get(0).toString();
activityName= list.get(5).toString();
activityAllocation= list.get(8).toString();
activityDate= list.get(10).toString();
activityPersonInCharge= list.get(11).toString();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/TEST", "root", "password");
System.out.println("connection made...");
PreparedStatement stmt=con.prepareStatement("INSERT INTO TEST_DEMO(ACT_ID,ACT_NAME,ACT_ALLOCATION,ACT_DATE,ACT_PERSON_ON_CHARGE) VALUES(?,?,?,?,?)");
stmt.setString(1, activityId);
stmt.setString(2, activityName);
stmt.setString(3, activityAllocation);
stmt.setString(4, activityDate);
stmt.setString(5, activityPersonInCharge);
stmt.executeUpdate();
System.out.println("Data is inserted");
stmt.close();
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
請提供日期格式部分一些線索。
在此先感謝。
你在哪裏Date是Strings?將它們保存爲日期 –
我可以舉個例子嗎?好的。如果我從字符串更改爲日期,那麼等號(=)後應該是什麼?對不起,仍然是這個新手。 –