我想做一個程序,我會從txt文件中讀取數據並將它們存儲在表中。用戶將給出文件的目錄,然後創建具有特定字段的表格。從表txt文件存儲數據mysql
然後我必須填寫每個表與它的數據。有沒有人可以幫助我如何做到這一點? .txt文件的數據與圖中所示的數據相同:
這兩列由製表符分隔。 我曾嘗試下面的代碼,但我得到的錯誤:
public class notepad {
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3300/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];
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());
}
showExcelData(sheetData);
getCreateTable1(con, tablename);
importData(con, txtFile);
}
}
}
}
} catch (Exception e) {
System.out.println();
}
}
private static String getCreateTable1(Connection con, String tablename) {
try {
Class.forName("com.mysql.jdbc.Driver");
Statement stmt = con.createStatement();
String createtable = "CREATE TABLE "
+ tablename
+ " (text VARCHAR(255), price int)";
System.out.println("Create a new table in the database");
stmt.executeUpdate(createtable);
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
private static void importData(Connection con, File txtFile) {
Statement stmt;
String query;
try {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
query = "LOAD DATA INFILE '" + txtFile
+ "' INTO TABLE tablename (text,price);";
stmt.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
stmt = null;
}
}
誰能幫助我,我會怎麼做:
java.sql.SQLException:at part1.importData(part1.java:31)
at part1.main(part1.java:16)
,我已經嘗試的代碼是?我的困難是當我想導入數據時。
請編輯您的文章。 SQL查詢中存在特定於SQL的錯誤。它與Java或JDBC無關。遠程java代碼,只留下查詢並重新發布到MySQL。首先嚐試從mysql控制檯調用命令以獲取更精確的SQL錯誤代碼。 –