Java regular expressions remove SQL comments from strings

I hope someone can help me solve this problem!

I have an SQL file that looks like this:

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');
*/

I have a web application that initializes a MySQL database with this function at startup:

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);
    }
}

(this function is found on the Internet. Author, please forgive me for not quoting your name, I lost it!!)

It works perfectly as long as there are no SQL comment blocks

The copytostring() function is basically what it says What I want now is to build a regular expression that will remove the block comment from the string I only have block comments / * * /, no -

What I've tried so far:

mySb = mySb.replaceAll("/\\*.*\\*/","");

Unfortunately, I'm not very good at regular expressions

I got "matching string looks like / * comment * / true statement / * another comment * /" and all the trouble... And so on

Solution

attempt

mySb = mySb.replaceAll("/\\*.*?\\*/","");

(note? Stands for "lazy")

Edit: to cover multiple lines of comments, use the following method:

Pattern commentPattern = Pattern.compile("/\\*.*?\\*/",Pattern.DOTALL);
mySb = commentPattern.matcher(mySb).replaceAll("");

I hope it works for you

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>