Batch processing JDBC statement improves processing speed

zhaozj2021-02-16  196

Sometimes JDBC is not fast enough, which makes some programmers use database-related stored procedures. As an alternative, you can try the batch processing characteristics of Statement to see if all SQL can be executed simultaneously to increase speed. The easiest form of the stored procedure is to include a series of SQL statements, which will be placed together for these statements to manage the same local management. The Statement class can include a series of SQL statements, so that all those statements that are allowed in the same database transaction rather than perform a series of calls to the database. Using batch processing functions involving two methods: addbatch (string) method · Executebatch method If you are using Statement, then addbatch method can accept a usual SQL statement, or if you are using preparedstatement, then you can nothing It increases. ExecuteBatch methods perform those SQL statements and return an array of int values, this array contains the number of rows affected by each statement. If you put a SELECT statement or other returns a SQL statement that returns a RESULTSET, it will cause an SQLException to exception. The simple example of java.sql.statement can be: statement stmt = conn.createstatement (); stmt.insert ("delete from users"); Stmt.insert ("Insert Into Uses Values", 37, "Circle ")"); Stmt.insert ("INSERT INTO Users Values ​​(" Jane ", 33," Triangle ")"); Stmt.Insert ("Insert Into Users Values ​​(" Freddy ", 29," Square ") Int [] counts = stmt.executebatch (); prepaaredStatement is somewhat different, it can only handle some SQL syntax, but there can many parameters, so some of the following results can be rewritten: // Note that there is no DELETE statement prepaaredStatement Stmt = conn.preparestatement ("Insert INTO Users VALUES (?,?,?)"); User [] users = ...; for (int i = 0; i

Stmt.setint (1, Users [i] .Getname ());

Stmt.setint (2, users [i] .getage ());

Stmt.setint (3, users [i] .getshape ());

Stmt.addbatch ();

}

Int [] counts = stmt.executebatch ();

If you don't know how many times your statement is to run, then this is a good way to handle SQL code. If you do not use batch processing, if you add 50 users, the performance has an impact. If someone wrote a script to add 10,000 users, the program may become very bad. Adding a batch function can help improve performance, and the readability of the code in the following cases is better.

转载请注明原文地址:https://www.9cbs.com/read-7949.html

New Post(0)