Java正则表达式从字符串中删除SQL注释
发布时间:2020-12-15 04:57:28 所属栏目:Java 来源:网络整理
导读:希望有人可以帮我解决这个问题! 我有一个看起来像这样的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 (first
希望有人可以帮我解决这个问题!
我有一个看起来像这样的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'); */ 我有一个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); } } (这个功能是在网上找到的.作者,请原谅我不引用你的名字,我丢了!!) 只要没有SQL注释块,它就能完美运行. copyToString()函数基本上就是它所说的. 到目前为止我尝试过的: mySb = mySb.replaceAll("/*.**/",""); 不幸的是,我不是很擅长正则表达式…… 我得到了“匹配的字符串看起来像/ *评论* /真实陈述/ *另一个评论* /”等所有麻烦……等等… 解决方法
尝试
mySb = mySb.replaceAll("/*.*?*/",""); (注意?代表“lazy”). 编辑:要涵盖多行注释,请使用以下方法: Pattern commentPattern = Pattern.compile("/*.*?*/",Pattern.DOTALL); mySb = commentPattern.matcher(mySb).replaceAll(""); 希望这对你有用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |