Java中的MySQL模式解析器? [英] A MySQL schema parser in Java?
问题描述
有人知道是否存在用于解析MySQL模式的Java库吗?在代码中,我希望能够确定模式中指定的表和字段.还是我需要自己写?
Does anyone know whether there is a java library for parsing a MySQL schema? In code I want to be able to determine the tables and fields specified in a schema. Or will I need to write my own?
感谢理查德.
只是想避免不必要地重新发明轮子:)
Just want to avoid re-inventing the wheel unnecessarily :)
推荐答案
回答我自己的问题:
我正在使用jsqlparser http://jsqlparser.sourceforge.net/
Am using jsqlparser http://jsqlparser.sourceforge.net/
这将解析单个语句,而不是模式中的多个语句.因此,请在;"上拆分模式.它还不喜欢'`'字符,因此需要将其删除.获取特定表的列名称的代码:
This parses individual statements, not multiple statements such as found in a schema. So split the schema on ';'. It also doesn't like the '`' character, so these need to be stripped out. Code to get column names for a particular table:
public class BUDataColumnsFinder {
public static String[] readSql(String schema) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(schema)));
String mysql = "";
String line;
while ((line = br.readLine()) != null) {
mysql = mysql + line;
}
br.close();
mysql = mysql.replaceAll("`", "");
return mysql.split(";");
}
public static List<String> getColumnNames(String tableName, String schemaFile) throws JSQLParserException, IOException {
CCJSqlParserManager pm = new CCJSqlParserManager();
List<String> columnNames = new ArrayList<String>();
String[] sqlStatements = readSql(schemaFile);
for (String sqlStatement : sqlStatements) {
Statement statement = pm.parse(new StringReader(sqlStatement));
if (statement instanceof CreateTable) {
CreateTable create = (CreateTable) statement;
String name = create.getTable().getName();
if (name.equalsIgnoreCase(tableName)) {
List<ColumnDefinition> columns = create.getColumnDefinitions();
for (ColumnDefinition def : columns) {
columnNames.add(def.getColumnName());
}
break;
}
}
}
return columnNames;
}
public static void main(String[] args) throws Exception {
String schemaFile = "/home/john/config/bu-schema.sql";
String tableName = "records";
List<String> columnNames = BUDataColumnsFinder.getColumnNames(tableName, schemaFile);
for (String name : columnNames) {
System.out.println("name: " + name);
}
}
}
这篇关于Java中的MySQL模式解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!