Excelファイルからデータを読み取ってテーブルに保存するプログラムを作成しています。私のファイルでは、一部のセルが空白になる可能性があり、それらをテーブルに null 値として保存していました。私のプログラムでは、LinkedHashMap を使用して各セルを読み取り、文字列として保存しています。私はプログラムを作成し、小さなExcelファイルをチェックして正常に動作しました。しかし、より大きなファイルでテストすると、次の例外が発生します。
SQLException: Column count doesn't match value count at row 1
SQLState: 21S01
VendorError: 1136
テーブルを埋めるためのコードは次のとおりです。
private static void fillTable(Connection con, String fieldname,
List<TableRow> allData) {
for (int row = 0; row < allData.size(); row++) {
LinkedHashMap<String, Integer> rowData = allData.get(row).tableFields;
Iterator iter = rowData.entrySet().iterator();
String str;
String[] tousFields = new String[rowData.size()];
int i = 0;
while (iter.hasNext()) {
Map.Entry pairs = (Map.Entry) iter.next();
Integer fieldType = (Integer) pairs.getValue();
String fieldValue = (String) pairs.getKey();
switch (fieldType) {
case Cell.CELL_TYPE_NUMERIC:
str = fieldValue;
break;
case Cell.CELL_TYPE_STRING:
str = "\'" + fieldValue + "\'";
break;
case Cell.CELL_TYPE_BOOLEAN:
str = fieldValue;
break;
case Cell.CELL_TYPE_BLANK:
str = "null";
break;
default:
str = "";
break;
}
tousFields[i++] = str;
}
try {
Statement stmt = con.createStatement();
String all = org.apache.commons.lang3.StringUtils.join(
tousFields, ",");
String sql = "INSERT INTO " + fieldname + " VALUES (" + all
+ ")";
stmt.executeUpdate(sql);
System.out.println("Fill table...");
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
}
}
テーブルを作成するコードは次のとおりです。
private static String getCreateTable(Connection con, String tablename,
LinkedHashMap<String, Integer> tableFields) {
Iterator iter = tableFields.keySet().iterator();
Iterator cells = tableFields.keySet().iterator();
String str = "";
String[] allFields = new String[tableFields.size()];
int i = 0;
while (iter.hasNext()) {
String fieldName = (String) iter.next();
Integer fieldType = (Integer) tableFields.get(fieldName);
switch (fieldType) {
case Cell.CELL_TYPE_NUMERIC:
str = fieldName + " INTEGER";
break;
case Cell.CELL_TYPE_STRING:
str = fieldName + " VARCHAR(255)";
break;
case Cell.CELL_TYPE_BOOLEAN:
str = fieldName + " INTEGER";
break;
case Cell.CELL_TYPE_BLANK:
str = "null";
break;
default:
break;
}
allFields[i++] = str;
}
try {
Class.forName("com.mysql.jdbc.Driver");
Statement stmt = con.createStatement();
try {
String all = org.apache.commons.lang3.StringUtils.join(
allFields, ",");
String createTableStr = "CREATE TABLE " + tablename + " ("
+ all + ")";
System.out.println("Create a new table in the database");
stmt.executeUpdate(createTableStr);
} catch (SQLException e) {
System.out.println("Error: the table already exists. Please try again " );
}
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return str;
}
誰でも私の問題を解決できますか?