我希望这次能收到我的答复。
我写了下面的代码,但不知道我的错误在哪里,我认为它似乎是正确的
这段代码应该会将超过百万条记录插入到oracle xe中。当逐条执行PreparedStatement时,我用一条insert语句编写了它,但它花了6个小时!因为我被迫使用thread.sleep()
package tokenizing;
import java.sql.*;
import java.util.StringTokenizer;
public class TokenExtraction2 {
public static void main(String[] args) throws Exception {
String myText[]=new String[2276];
Jdbc db=new Jdbc();
String st1=null;
int i=0;
int j=0;
String tokens[][]=new String [3000000][2];
st1="select ntext from NEWSTEXT ";
ResultSet result=db.select(st1);
while(result.next())
{
myText[i]=result.getString("ntext");
++i;
}
db.closedb();
i=0;
StringBuilder st= new StringBuilder("insert into tokens5(token,tokenlength) values");
while(i<2276)
{
StringTokenizer s=new StringTokenizer(myText[i]," 0123456789*./»«،~!@#$%^&()_-\"+=:;|<>?“؟”’{}[]‘,\\\t\n\r\fabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ...—`—ـ؛–…_");
while(s.hasMoreTokens()){
String key=s.nextToken();
tokens[j][0]=key;
tokens[j][1]=(key.length())+"";
st.append("(?,?)");
if( i<2276 && s.hasMoreTokens())
st.append(", ");
else
st.append(";");
//db.insert(st, key, key.length());
//db.closedb();
System.out.println(key+"\t");
j++;
}
System.out.println("num of news is: "+i);
System.out.println("*****************************************************************************************");
System.out.println("num of tokens is: "+j);
System.out.println("next news"+"\t");
//j=0;
i++;
}
System.out.println(st);
int k=0;
Class.forName("oracle.jdbc.driver.OracleDriver") ;
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","ALBALOO","myjava123");
PreparedStatement ps=con.prepareStatement(st.toString());
// con.setAutoCommit(false);
//j=1;
i=0;
//j=j-286;
while(k<j)
{
i=i+1;
ps.setString(i, tokens[k][0]);
System.out.println(i);
i=i+1;
ps.setInt(i,Integer.parseInt(tokens[k][1]));
System.out.println(k+2);
k++;
}
ps.executeUpdate();
//con.commit();
}
}发布于 2013-07-24 03:24:13
如果查看SQL中的Oracle INSERT description,就会发现Oracle不支持使用VALUES插入多行。同样,正如我上面所说的,在查询中使用;并不总是有效的,因为它通常不是查询本身的一部分,而是命令行或脚本输入的终止符。
在您的特定情况下,您甚至尝试将多个语句放入一个prepare中。在JDBC中,单个语句prepare (或execute)应该只是一个实际语句,而不是由;分隔的多个语句。驱动程序(或数据库)通常不允许这样做,尽管有些驱动程序提供了执行多个语句的选项,但这并不符合JDBC。
相反,您可以使用JDBC批处理更新:
con.setAutoCommit(false);
try (
PreparedStatement pstmt = con.
prepareStatement("insert into tokens5(token,tokenlength) values (?, ?)"
) {
// I use tokens as an abstraction on how you get the token and its length
while (tokens.next()) {
pstmt.setString(1, tokens.token());
pstmt.setInt(2, tokens.length());
pstmt.addBatch();
};
pstmt.executeBatch();
// Optionally do something with result of executeBatch()
con.commit();
}根据database+driver的不同,这将具有与多值插入类似的运行时性能(我相信在Oracle中是这样的),或者只是表现为您使用不同的值多次执行单个PreparedStatement。
https://stackoverflow.com/questions/17818536
复制相似问题