2011-12-16 23 views
-1

可能重複:
SQL parser library for Java與Java解析SQL文件,並獲得發言和評論

我想用現成的解決方案解析SQL文件。文件可以包含註釋,SQL語句,DDL。 我需要得到評論,所有的SQL語句。 沒有人知道現成的解決方案嗎?我不想再多一個方形輪..

P.S. 請注意,我不需要忽視評論,我需要從文件中的評論中獲取文本

+3

它已被問到http://stackoverflow.com/questions/660609/sql-parser-library-for-java – 2011-12-16 07:55:21

+0

http://stackoverflow.com/q/660609/108341 – 2011-12-16 07:56:17

回答

1

對於什麼是值得的,我建議你看一看iBatis,其中恕我直言,讓手寫DAO和DTO與JDBC完全過時。

在使用iBatis之前,我將SQL保存在單獨的SQL文件中,並在需要時檢索正確的SQL。我不再使用它了,因爲這在實際的Java代碼中只比SQL稍好一些。

SQL文件的語法如下:

-- I added comments like this... 
[id] { 
    any SQL statement... (quite frankly any text). 
} 

[id2] { 
    ... 
} 

... 

然後,一個簡單的解析器類如下:

public class SQLParser { 
    private static Logger logger = LoggerUtility.getLogger(SQLParser.class); 

    private String raw; 
    private Map<String, String> sql; 

    public SQLParser(InputStream is) { 
     sql = new HashMap<String, String>(); 
     try { 
      read(is); 
      parse(); 
     } catch (IOException e) { 
      logger.debug(LoggerCodes.TRACE, "Input Stream could not be successfull read!"); 
     } 
    } 

    private void read(InputStream is) throws IOException { 
     StringBuilder builder = new StringBuilder(); 
     BufferedReader in = new BufferedReader(new InputStreamReader(is)); 
     String line = in.readLine(); 
     while (line != null) { 
      builder.append(line + "\n"); 
      line = in.readLine(); 
     } 
     raw = builder.toString(); 
    } 

    public String getSql(String sqlId) { 
     return sql.get(sqlId); 
    } 

    public PreparedStatement getSql(Connection connection, String sqlId) throws SQLException { 
     String statement = sql.get(sqlId); 
     return connection.prepareStatement(statement); 
    } 

    private void parse() { 
     if (raw == null) { 
      logger.debug(LoggerCodes.TRACE, "No String to parse for SQL statements!"); 
      return; 
     } 

     String regex = "\\.*\\[(\\S*)\\]\\s*\\{\\s*([^\\}]*)\\s*\\}"; 
     Pattern p = Pattern.compile(regex); 
     Matcher m = p.matcher(raw); 
     while (m.find()) { 
      String key = m.group(1); 
      String body = m.group(2); 
      logger.debug("Adding " + key + " to SQL map."); 
      sql.put(key, body.trim()); 
     } 
    } 
} 

然後只需創建上面的一個新的實例,並調用sqlParser .getSql(id)獲取正確的SQL。