我正在创建一个程序,我从.txt文件中读取数据并将它们存储在表中。在我的程序中,用户将给出文件的目录,程序将找到所有.txt文件,并且对于这些文件中的每一个都将创建一个表,该表将具有文件名称的名称,并且每个表将具有两个字段(文字和价格)。
这两列由空格分隔。在我的代码中显示了所有程序。但是当我尝试以编程方式导入数据时,我遇到了问题。我得到的错误异常是我在SQL语法中有错误。任何人都可以帮助我,因为我试图解决它几天没有结果?
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:3330/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();
String filename = dirpath.substring(dirpath
.indexOf('\\') - 2, files
.indexOf(parts[0]));
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
getCreateTable1(con, tablename);
importData(con, txtFile, tablename);
}
}
}
}
} 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 String importData(Connection con, File txtFile,
String tablename) {
try {
Statement stmt;
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String importingdata = "LOAD DATA INFILE '"
+ txtFile.getAbsolutePath() + "' INTO TABLE '" + tablename
+ " (text,price)";
stmt.executeUpdate(importingdata);
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
}
答案 0 :(得分:1)
尝试更改
+ txtFile.getAbsolutePath() + "' INTO TABLE '" + tablename
^
到
+ txtFile.getAbsolutePath() + "' INTO TABLE " + tablename
此孤立报价会使您的对帐单无效。