->arne_v:
Ja, PreparedStatement giver i første omgang ikke noget særligt:
import java.sql.*;
public class Testing2 {
public static void main(String[] args) throws Exception {
int antal=1000;
long starttid, sluttid;
starttid = System.currentTimeMillis();
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:
mysql://localhost/test");
Statement stmt=conn.createStatement();
stmt.executeUpdate("drop table test1");
stmt.executeUpdate("create table test1 (i int, v varchar(12))");
PreparedStatement pstmt=conn.prepareStatement("insert into test1 values(?,?)");
for (int i=0;i<antal;i++) {
pstmt.setInt(1,i);
pstmt.setString(2,"Hej");
pstmt.executeUpdate();
}
stmt.close();
conn.close();
sluttid = System.currentTimeMillis();
System.out.println("Testing2: "+(sluttid-starttid)*0.001 +" sek.");
}
}
Men som du skriver, giver det en meget kraftig forbedring at slå autocommit fra:
import java.sql.*;
public class Testing3 {
public static void main(String[] args) throws Exception {
int antal=100000;
long starttid, sluttid;
starttid = System.currentTimeMillis();
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:
mysql://localhost/test");
conn.setAutoCommit(false);
Statement stmt=conn.createStatement();
stmt.executeUpdate("drop table test1");
stmt.executeUpdate("create table test1 (i int, v varchar(12))");
for (int i=0;i<antal;i++) {
stmt.executeUpdate("insert into test1 values ("+i+",'Hej')");
}
conn.commit();
conn.setAutoCommit(true);
stmt.close();
conn.close();
sluttid = System.currentTimeMillis();
System.out.println("Testing3: "+(sluttid-starttid)*0.001 +" sek.");
}
}
Og endelig med både PreparedStatement og autocommit slået fra fås bedste performance:
import java.sql.*;
public class Testing4 {
public static void main(String[] args) throws Exception {
int antal=100000;
long starttid, sluttid;
starttid = System.currentTimeMillis();
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:
mysql://localhost/test");
conn.setAutoCommit(false);
Statement stmt=conn.createStatement();
stmt.executeUpdate("drop table test1");
stmt.executeUpdate("create table test1 (i int, v varchar(12))");
PreparedStatement pstmt=conn.prepareStatement("insert into test1 values(?,?)");
for (int i=0;i<antal;i++) {
pstmt.setInt(1,i);
pstmt.setString(2,"Hej");
pstmt.executeUpdate();
}
conn.commit();
conn.setAutoCommit(true);
stmt.close();
conn.close();
sluttid = System.currentTimeMillis();
System.out.println("Testing4: "+(sluttid-starttid)*0.001 +" sek.");
}
}
Smid gerne et svar.