希望有人可以帮我解决这个问题!
我有一个看起来像这样的sql文件:
CREATE TABLE IF NOT EXISTS users(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT UNIQUE (firstname,lastname)
)
ENGINE=InnoDB
;
INSERT IGNORE INTO users (firstname,lastname) VALUES ('x','y');
/*
INSERT IGNORE INTO users (firstname,lastname) VALUES ('a','b');
*/
Run Code Online (Sandbox Code Playgroud)
我有一个web应用程序,它在启动时用这个函数初始化一个mysql数据库:
public static void initDatabase(ConnectionPool pool, File sqlFile){
Connection con = null;
Statement st = null;
String mySb=null;
try{
con = pool.getConnection();
mySb=IOUtils.copyToString(sqlFile);
// We use ";" as a delimiter for each request then we are sure to have well formed statements
String[] inst = mySb.split(";");
st = con.createStatement();
for(int i = 0; i<inst.length; i++){
// we ensure that there is no spaces before or after the request string
// in order not to execute empty statements
if(!inst[i].trim().isEmpty()){
st.executeUpdate(inst[i]);
}
}
st.close();
}catch(IOException e){
throw new RuntimeException(e);
}catch(SQLException e){
throw new RuntimeException(e);
}finally{
SQLUtils.safeClose(st);
pool.close(con);
}
}
Run Code Online (Sandbox Code Playgroud)
(这个功能是在网上找到的.作者,请原谅我不引用你的名字,我丢了!!)
只要没有SQL注释块,它就能完美运行.
该copyToString()功能基本上完成它所说的.我现在想要的是构建一个将从字符串中删除块注释的正则表达式.我只/* */在文件中有块注释,没有--.
到目前为止我尝试了什么:
mySb = mySb.replaceAll("/\\*.*\\*/", "");
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不是很擅长正则表达式......
我得到了"匹配的字符串看起来像/* comment */ real statement /* another comment*/"的所有麻烦等等......
尝试
mySb = mySb.replaceAll("/\\*.*?\\*/", "");
Run Code Online (Sandbox Code Playgroud)
(注意?哪个代表" 懒惰 ").
编辑:要涵盖多行注释,请使用以下方法:
Pattern commentPattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL);
mySb = commentPattern.matcher(mySb).replaceAll("");
Run Code Online (Sandbox Code Playgroud)
希望这对你有用.
| 归档时间: |
|
| 查看次数: |
4461 次 |
| 最近记录: |