中的「問題」我正在製作一個程序,我將從文本文件中讀取數據並將表存儲在mysql中。在我的文件中的數據如圖所示:在插入表
該程序必須做的是,首先用戶提供目錄,程序搜索其中的文本文件,然後創建一個有兩個字段(ID ,NAME),然後在其中插入值。所有文件具有相同的結構。該ID在第三行中,並且該名稱在第五行中。
任何人都可以幫助我在表中插入這些值的查詢?我的代碼中的「錯誤」在哪裏? 我的程序代碼是以下:
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3808/mydb", "root", "root");
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
if (fl.canRead())
break;
System.out.println("Error:Directory does not exists");
}
try {
String files;
File folder = new File(dirpath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
List<File> txtFiles = new ArrayList<File>();
txtFiles.add(listOfFiles[i]);
String[] parts = files.split("\\.");
String tablename = parts[0];
DatabaseMetaData dm = (DatabaseMetaData) con
.getMetaData();
ResultSet rs = dm
.getTables(null, null, tablename, null);
if (!rs.next()) {
System.out.println("The table '" + tablename
+ "' just created. The data are:");
} else {
System.out.println("The table '" + tablename
+ "' already exists.");
continue;
}
for (File txtFile : txtFiles) {
List sheetData = new ArrayList();
try {
FileReader in = new FileReader(txtFile);
BufferedReader br = new BufferedReader(in);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
getCreateTable1(con, tablename);
{
BufferedReader br = new BufferedReader(
new FileReader((txtFile)));
String currentLine = br.readLine();
Map<Integer, String> Fields = new HashMap<Integer, String>();
while (currentLine != null) {
String[] tokens = currentLine.split("\t");
int id = Integer.parseInt(tokens[2]);
String name = tokens[4];
Fields.put(id, name);
currentLine = br.readLine();
}
}
importData(con, txtFile, tablename);
}
}
}
}
} catch (Exception e) {
System.out.println();
}
}
和進口的函數的代碼是:
private static String importData(Connection con, File txtFile,
String tablename) {
Map<Integer, String> Fields = new HashMap<Integer, String>();
try {
Statement stmt = con.createStatement();
String all = org.apache.commons.lang3.StringUtils.join(Fields, ",");
String sql = "INSERT INTO " + tablename + " VALUES (" + all + ")";
stmt.executeUpdate(sql);
System.out.println("Fill table...");
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
}
http://stackoverflow.com/questions/17168108/how-get-values-for-table-from-specific的可能重複的輸入參數-row-in-text-files –
這裏是關於在表格中插入值的功能。 – dedmar
然後請減少那段代碼並專注於該功能 –