What does %s(%s) specifier do?

87 views Asked by At

I have a function that writes a sql query

I can't figure out what does the expression %s(%s) do in this function

public void createTable(String tabName) throws SQLException {
    String sql = "create table if not exists %s(%s)";
    sql = String.format(sql,
                        tabName,
                        String.format("%s,%s,%s,%s,%s,%s,%s",
                        "id int primary key auto_increment",
                        "surname varchar(50)",
                        "name varchar(50)",
                        "age int(3)",
                        "course int(1)",
                        "group varchar(50)",
                        "stateFunded int(1)"
                ));
    stat.execute(sql);
    System.out.println(sql);
}

I've tried to search, but there is no information about it in Google.

1

There are 1 answers

2
Federico klez Culloca On BEST ANSWER

By itself %s(%s) is simply two string placeholder one after the other, with the second being surrounded by parentheses that have no syntactic meaning as far as format is concerned.

What this piece of code does is simply substituting the content of tabName for the first %s and the result of

String.format("%s,%s,%s,%s,%s,%s,%s",
                    "id int primary key auto_increment",
                    "surname varchar(50)",
                    "name varchar(50)",
                    "age int(3)",
                    "course int(1)",
                    "group varchar(50)",
                    "stateFunded int(1)")

for the second one, hence creating something along the lines of

create table if not exists tabName(
    id int primary key auto_increment,
    surname varchar(50),
    name varchar(50),
    age int(3),
    course int(1),
    group varchar(50),
    stateFunded int(1)
)

for whatever value tabName has.