0

I have a table on mySql with around 300,000 records. One column is a VARCHAR and it contains a link (let's say, http://www.mysite.com/123012993)

Using Java, everytime I create a new record I need to know if it already exists. The exact link must be on the database. If it's new, then proceed to insert. Else, do nothing.

So I have the following:

String selectString = "Select count(link) from records_table where link = ?";
        PreparedStatement ps = conn.prepareStatement(selectString);
ps.setString(1, "http://www.mysite.com/123012993");
ResultSet rsFinding = ps.executeQuery();

rsFinding.next();

if (t != 0) return false;
else { // do normal insert }

However, the query to search the Text is very slow, we are talking around 1 minute. The insert itself is very fast. Everything runs on localhost.

Is this the right way to search for the text? Or should I index the database?

I was thinking on implementing a hashkey and narrow the results, but a query on 300,000 records shouldn't be to heavy I believe.

Thanks

4

1 回答 1

2

有几件事:

  • PreparedStatement不应该一次又一次地准备。准备和重用。
  • t的定义无处不在。
  • 让数据库完成工作:我猜每个数据库都有可能处理重复项。对于 MySql 有INSERT ... ON DUPLICATE KEY UPDATE ...

所以使用这个命令

INSERT ? INTO records_table ON DUPLICATE KEY UPDATE link = link

该部分link = link是使语法看起来适合 MySql 解析器的无操作。

还有INSERT IGNORE一个更容易使用(不需要无操作),但它忽略了更多问题,这很糟糕。

我忘了提到你需要一个唯一的键约束link(主键是英国的一个特例,因此也很好)。

于 2013-10-16T22:15:56.443 回答