【发布时间】:2020-09-02 13:11:49
【问题描述】:
我想创建测试数据并编写了一个用于存储产品的函数,我的产品生成器在我的数据库中生成。
该计划是为了测试目的创建大约 10,000,000 个或更多产品。
我想在每次插入产品之前检查是否存在相同的产品名称。
如果是,则产品不会存储在数据库中。 我知道性能问题是检查产品是否存在,数据库中的产品越多,这需要的时间就越长。但我知道,没有其他办法可以改善这个问题。 我可能会使用索引,但我不知道如何在这种情况下使用。 如果您对如何提高性能有其他想法,请随时评论您的想法。
tldr:我想创建 testdata,但它确实需要很长时间,因为它正在检查产品是否已经存在。想要提高性能。
这是我的代码:
public String insertProdukt(String name, Double preis, Integer kat_id) throws SQLException, ClassNotFoundException {
Connection connection = ConnectionUtils.createNewConnection();
// does the product exist?
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from pro_produkte where pro_name=\"" + name + "\" AND pro_preis=\"" + preis + "\" AND pro_kat_id=\"" + kat_id + "\"");
if (resultSet.next()) {
//it does exist
System.out.println("Produkt: " + resultSet.getString("pro_name") + " existiert bereits");
} else {
//it dosen't -> insert into database
String sql = "Insert INTO pro_produkte (pro_name, pro_preis, pro_kat_id)"
+ "VALUES (\"" + name + "\", \"" + preis + "\", \"" + kat_id + "\")";
statement.executeUpdate(sql);
System.out.println("Produkt: " + name + " erstellt");
}
resultSet.close();
statement.close();
connection.close();
return null;
}
谢谢!
【问题讨论】:
-
在你做任何事情之前,了解准备好的语句和占位符值,因为这段代码中充满了SQL injection bugs。
-
如果要插入大量数据,可以考虑使用
LOAD DATA INFILE。 -
@tadman 感谢您的提示,将其合并到我的代码中。
标签: java mysql sql performance mariadb