我有一个名为H2的PRODUCTS数据库,它有5000行和每行55列。我目前正在使用PreparedStatement向数据库添加值行,但它不检查该行是否已经存在。相反,如果列名"id“(类型为VARCHAR)不包含某个alpha-数字字符串,如果列名"id2”(类型为VARCHAR)不包含某个α-数字字符串,以及如果列名"raw_yn“(类型为布尔型)包含false,则只需要插入行。我输入到准备语句中的值是通过一种方法提供的。
这里的问题非常接近我所问的问题,区别在于它的解决方案是基于向空DB添加行,并确保数据库是空的。H2的创建者评论道:
然后,"where not“确保只在表为空的情况下插入此行。
如何调整这段代码,使其仅在满足上述3项要求(无论DB是否为空)时执行INSERT查询?
目前我有:
import java.sql. *;
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/myDB";
static final String USER = "test";
static final String PASS = "test";
static final Connection conn = null;
static final Statement stmt = null;
public class DataBaseManager {
public void insertIntoDB(String id1val, String id2val, Boolean raw_yn_val, ...,...) {
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
myStatement = "INSERT INTO PRODUCTS VALUES(?,?,?,..,...)";
stmt = conn.prepareStatement(myStatement);
stmt.setString(1, id1val);
stmt.setString(2, id2val);
stmt.setBoolean(3, raw_yn_val);
stmt.setString(4,....);
// Continue up to 55
stmt.executeUpdate();
}
[catch&finally blocks]
}
}myStatement应该改为什么?我很困惑,因为如果我像下面这样使用select 0, 'id1' union,它如何适合于我的PreparedStatement of stmt.setString(1, id1val);?谢谢你的帮助。
INSERT INTO PRODUCTS SELECT * FROM(
select 0, 'id1' union // <--- How does this fit into Prepared Statement?
select 1, 'id2' union
select 2, 'raw_yn' union
) x where not exists(SELECT * FROM PRODUCTS); // <--- Ensures only works when empty更新:
按照Gord的建议,我编写了以下代码。如果数据库为空,n将返回0。这大约需要1分钟才能将5000行添加到空数据库。但是,如果有匹配,则需要花费近5倍的时间,尽管我只是使用return,而不是使用额外的INSERT代码。所以它不应该更快吗?
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
statement = conn.createStatement();
String sql = "SELECT COUNT(*) AS n FROM PROPERTIES WHERE id1='" + id1 + "' AND id2='" + id2 + "' AND raw_yn='true'";
rs = statement.executeQuery(sql);
rs.next();
if (rs.getInt("n") == 0) {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
myStatement = "INSERT INTO PROPERTIES VALUES(?,?,?,...)";
stmt = conn.prepareStatement(myStatement);
stmt.setString(1, id1);
stmt.setString(2, id2);
stmt.setBoolean(3, raw_yn);
stmt.executeUpdate();
} else {
return; // <-- Takes 5x longer to go through ???
}
}
[catch & finally blocks]发布于 2016-07-23 18:29:32
考虑使用临时表,其中将所有数据附加到类似的结构化表ProductsTemp中,然后迁移到最终表,产品,为唯一的行过滤。下面是按以下顺序合并到Java代码中的SQL语句:
分阶段追加(两条语句)
DELETE FROM ProductsTemp;
INSERT INTO ProductsTemp VALUES (?,?,?,..,...);最终迁移
INSERT INTO Products (id, id2, raw_yn, ...)
SELECT id, id2, raw_yn, ...
FROM ProductsTemp temp
WHERE NOT EXISTS (SELECT 1 FROM Products sub
WHERE sub.id = temp.id
AND sub.id2 = temp.id2
AND sub.raw_yn = temp.raw_yn);https://stackoverflow.com/questions/38544120
复制相似问题