如何在postgresql表中插入java数据生成函数?

mnemlml8  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(334)

我有postgresqldb,我使用jdbc连接并生成表,但我想生成带有随机数据的表。因此,我创建了java方法,它生成随机名称和姓氏,我想将它们设置到我的表中的特殊列(name,姓氏)。我的数据库:

DROP TABLE IF EXISTS groups;
CREATE TABLE groups(
name VARCHAR(50),
surname VARCHAR(50),
);

我试着用这个代码来设置姓名:

String URL = "jdbc:postgresql://localhost:5432/school";
    String user = "principal";
    String password = "123";

    String sqlScript = new String(Files.readAllBytes(Path.of("src/main/resources/database/dbScript.sql")));

    Connection connection = DriverManager.getConnection(URL, user, password);
    System.out.println("Success.........");
    Statement script = connection.createStatement();
    script.execute(sqlScript);
    //class with random gen.
    StudentsGenerator generator = new StudentsGenerator();

    String query1 = "INSERT INTO groups " +"VALUES (generator.student().stream().map(names -> names.getName()))";
    script.executeUpdate(query1);
frebpwbc

frebpwbc1#

如果 INSERT 允许有多个值的语句:

INSERT INTO tbl_name (col1, col2) VALUES 
('val11', 'val12'),
('val21', 'val22'),
...
('valN1', 'valN2');

可以生成这样的语句:

String manyInserts = "INSERT INTO groups VALUES " 
    + students.stream()
              .map(student -> String.format("('%s', '%s')", student.getName(), student.getSurname()))
              .collect(Collectors.joining(","));
script.executeUpdate(manyInserts);

但是,这种方法不受sql注入的保护,因此更可取的做法是使用批插入来实现 PreparedStatement :

PreparedStatement ps = connection.prepareStatement("INSERT INTO groups (name, surname) VALUES (?, ?)");
students.forEach(student -> {
    ps.setString(1, student.getName());
    ps.setString(2, student.getSurname());
    ps.addBatch();
});
ps.executeBatch();

相关问题