vendredi 17 février 2023

Loading files - pattern

I am currently dealing with the fact that I have to import about 15 csv files into db tables. Each csv file already has its own db table. The code for filling the table works for me, see below.

public class Loader {
        public void load(Connection conn, String file, String[] columns, String tableName) {
            String sqlLoadData = "LOAD DATA LOCAL INFILE " +
                    file +
                    " INTO TABLE " +
                    tableName +
                    " FIELDS TERMINATED BY " +
                    "';' " +
                    "LINES TERMINATED BY " +
                    "'\n' " +
                    "IGNORE 2 ROWS " +
                    Stream.of(columns).collect(Collectors.joining(", ", "(", ")"));
    
            try (PreparedStatement ps = conn.prepareStatement(sqlLoadData)) {
                ps.setInt(1, packageInfo.getIdPackage());
                ps.execute();
            }
        }
    }

Loading files

Loader loader = new Loader();
loader.load(conn, "user.csv", new String[] { "firstName", "lastName"});
loader.load(conn, "permissions.csv", new String[] { some columns });
loader.load(conn, "roles.csv", new String[] { some columns });
// calling for next files

I don't like this solution. I'm still thinking about a suitable way to do some encapsulation in trid instead of calling the Loader.load method. I went through the design patterns, but I couldn't match any of them to my problem. Can you give me some advice?

Aucun commentaire:

Enregistrer un commentaire