日期:2014-05-16 浏览次数:20530 次
public class ParseDBStructFile {
/**
* 读取Sql文件,得到Sql语句信息列表
* @param operation 控制Sql语句的数组
* @param filename Sql文件所在的路径
* @return Sql语句的信息列表
*/
@SuppressWarnings("unchecked")
public static List parse(String[] operation,String filename) {
//保存Sql语句的List
List statements = new ArrayList();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
StringBuffer sb = new StringBuffer(512);
boolean processing = false;
char delimiter = ';';
// String[] creators = { "CREATE INDEX", "CREATE TABLE",
// "CREATE SEQUENCE", "DROP TABLE", "IF EXISTS",
// "DROP SEQUENCE", "DROP INDEX" };
String[] creators = operation;
String line;
while ((line = reader.readLine()) != null) {
if (line.length() == 0) {
continue;
}
char charAt = line.charAt(0);
// Ignore comments
if (charAt == '-' || charAt == '#') {
continue;
}
if (processing) {
sb.append(line);
if (line.indexOf(delimiter) > -1) {
sb.delete(sb.length() - 1, sb.length());
statements.add(sb.toString());
processing = false;
}
} else {
for (int i = 0; i < creators.length; i++) {
if (line.indexOf(creators[i]) > -1) {
sb.delete(0, sb.length());
if (line.indexOf(delimiter) > -1) {
if (line.indexOf(';') > -1) {
line = line.replace(';', ' ');
}
statements.add(line);
} else {
sb.append(line);
processing = true;
}
break;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
}
}
}
return statements;
}
}
public class InstallTables {
/**
* 创建数据库表的方法
* @param post 数据库对应的端口
* @param dbName 数据库名称
* @param username 用户名
* @param password 密码
* @param operation 控制数据库创建表数组
* @param filename Sql表文件的路径
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void install(String post,String dbName,String username,String password,String[] operation,String filename) throws Exception{
Connection conn = DBConnection.getConnectionMySqlDB(post,dbName,username,password);
boolean autoCommit = conn.getAutoCommit();
Statement st = null;
List queryList = ParseDBStructFile.parse(operation,filename);
for(String sql:queryList){
if (sql == null || "".equals(sql.trim())) {
continue;
}
st = conn.createStatement();
st.executeUpdate(sql);
st.close();
}
conn.setAutoCommit(autoCommit);
}
}
public class DBConnection {
public static Connection getConnectionMySqlDB(String post, String dbName,String userName,String password)
throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:" + post + "/" + dbName;
String user = userName;
String pwd = password;
Class.forName(driver);
return DriverManager.getConnection(url, user, pwd);
}
}
public class testCreator{
@Test
public void testInstallTables(){
InstallTables install = new InstallTables();
try {
String[] operation = {"CREATE TABLE","DROP TABLE"};
install.install("3306", "jackdemo", "root", "jack",operation, "F: