2013-06-04 5 views
0

.txt 파일의 데이터를 읽고 테이블에 저장하는 프로그램을 만들고 있습니다. 내 프로그램에서 사용자는 파일의 디렉토리를 줄 것이고, 프로그램은 모든 .txt 파일을 찾을 것이고, 각각의 파일에 대해 파일 이름에 이름을 가진 테이블을 만들 것이며 각 테이블은 두 개의 필드를 가질 것이다. 텍스트 및 가격).mysql에서 테이블의 데이터를 가져 오는 중 예외가 발생했습니다.

이 두 열은 공백으로 구분됩니다. 아래 코드는 모든 프로그램을 보여줍니다. 하지만 프로그래밍 방식으로 데이터를 가져 오려고 할 때 문제가 있습니다. 오류 예외는 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

스택 추적과 함께 우리에게 예외를 보여줍니다 ... 또한 테이블을 생성하거나 데이터를로드 할 때 ex가 발생합니다. – Stephan

+0

데이터를로드 할 때 오류가 발생합니다. "SQL 구문에 오류가 있습니다. 오른쪽 구문을 보려면 MySQL 서버 버전에 해당하는 설명서를 확인하십시오. 1 com.mysql.jdbc.exceptions.jdbc4 줄의 'temp (text, price)'근처에서 사용하십시오. MySQLSyntaxErrorException : SQL 구문에 오류가 있습니다. 올바른 구문이 "temp (text, price)"근처에서 사용하도록 MySQL 서버 버전에 해당하는 설명서를 확인하십시오. " – dedmar

답변

1

이 고아 견적 명세서가 유효하게

+ txtFile.getAbsolutePath() + "' INTO TABLE '" + tablename 
              ^

+ txtFile.getAbsolutePath() + "' INTO TABLE " + tablename 

하려고 변화.

+0

이제 java.sql을 얻습니다. .SQLException : 파일 'C : \ 경우 ProgramData \ MySQL은 \ MySQL 서버 5.6 \ 데이터 \ UsersDocumentstest \t emp.txt'(errcode를 : 22 - 잘못된 인수)를 찾을 수 없습니다 – dedmar

+0

을 경로이 있어야한다 : 'C : \ 경우 ProgramData \ MySQL은 \ MySQL을 Server 5.6 \ data \ UsersDocuments \ test emp.txt' – Stephan

+1

@dedmar 이는 귀하의 질문에 대한 귀하의 진술이 마침내 작동하고 있음을 말해줍니다. 하지만 문제는 mysql이 지정한 파일을 읽을 수 없다는 것입니다. 경로 및 (또는) 파일 이름이 잘못 되었기 때문일 수 있습니다 (Stephan이 언급 한 것처럼). – peterm