Java -- JDBC Summary (5), javajdbc Summary

Source: Internet
Author: User

Java -- JDBC Summary (5), javajdbc Summary
1. Transactions

There are many concepts and principles about things, but my understanding is one sentence. To maintain a integrity is one thing, which should be completed in several steps, however, it is complete to complete these steps. The simplest example here is to simulate the withdrawal and deposit of a bank. I will give this sample code and analyze it.

1 @ Test 2 public void test2 () {3 String payId = "00001"; 4 String recId = "00002"; 5 double mny = 1000; 6 Connection conn = null; 7 try {8 conn = DBUtil. getConnection (); 9 String SQL = "select * from accounts_jiawen" 10 + "where id =? "; 11 PreparedStatement ps = conn. prepareStatement (SQL); 12 ps. setString (1, recId); 13 ResultSet rs1_ps.exe cuteQuery (); 14 if (! Rs. next () {15 System. out. println ("the receiving account does not exist"); 16 throw new SQLException ("the receiving account does not exist"); 17} 18 // record the recipient's balance 19 double recMoney = rs. getDouble ("money"); 20 21 // set to manually manage transaction 22 conn. setAutoCommit (false); 23 24 // 2. verify that the payer balance is sufficient. 25 SQL = "select * from accounts_jiawen" 26 + "where id =? "; 27 ps = conn. prepareStatement (SQL); 28 ps. setString (1, payId); 29 rs1_ps.exe cuteQuery (); 30 rs. next (); 31 double payMoney = rs. getDouble ("money"); 32 if (payMoney <mny) {33 System. out. println ("insufficient balance"); 34 throw new SQLException ("insufficient balance"); 35} 36 37 38 39 // 3. the payer's balance is reduced by n RMB 40 SQL = "update accounts_jiawen set" 41 + "money =? Where id =? "; 42 ps = conn. prepareStatement (SQL); 43 ps. setDouble (1, payMoney-mny); 44 ps. setString (2, payId); 45 ps.exe cuteQuery (); 46 47 // assume there is an error 48 // Integer. valueOf ("abc"); 49 // 4. the cashier adds n RMB 50 SQL = "update accounts_jiawen set" 51 + "money =? Where id =? "; 52 ps = conn. prepareStatement (SQL); 53 ps. setDouble (1, recMoney + mny); 54 ps. setString (2, recId); 55 ps.exe cuteQuery (); 56 // submit transaction 57 conn when the transfer process ends normally. commit (); 58} catch (Exception e) {59 // rollback transaction 60 try {61 conn when an Exception occurs during the transfer. rollback (); 62} catch (SQLException e1) {63 // TODO Auto-generated catch block64 e1.printStackTrace (); 65 throw new RuntimeException ("rollback "); 66} 67 e. printStackTrace (); 68 throw new RuntimeException ("wrong", e); 69} finally {70 DBUtil. close (conn); 71} 72}

 

First, we need to simulate the accounts of two banks and send money to the other. First, we need to query the recipient's information. This is in line with the century's logic, because we need to know whether the recipient exists, the select query statement still uses the aforementioned ParperdStatement. It sets a placeholder to determine whether the payee exists and records the current balance of the payee, so that you can accumulate the money.

Next, let's focus on the second line. This is to manually manage a transaction and disable automatic management of the transaction, so that the above code is not a matter of complete opinions, otherwise, he will be the complete one, instead of waiting for the following process, but in fact, the collection and remittance can be considered as a whole, because this involves two people's account amount changes, you can't just consider the change in the amount of one person, but set it to false, the above process will wait for the following process together. The second part is to verify the payer's balance and determine whether the transfer is sufficient. The subsequent process is to change the amount of both parties. If you do not set the transaction as manual, simulate a code above step 4 to interrupt the execution of the lower-end code in the pipeline, the subsequent amount will be incorrect. It must be noted that conn. commit () is a unified commit transaction, and conn. rollback () is a rollback.

2. Batch Processing

By name, it means to send a group of SQL statements together in a centralized manner, which improves efficiency and reduces network calls between databases and programs. The sample code is provided directly:

@ Test public void test3 () {Connection conn = null; try {conn = DBUtil. getConnection (); conn. setAutoCommit (false ); // The premise for sending data in batches is that their SQL is the same as String SQL = "insert into emp_jiawenzhe values (" + "emp_jiawenzhe_1_nextval ,?,?,?,?,?,?,?) "; PreparedStatement ps = conn. prepareStatement (SQL); for (int I = 1; I <= 108; I ++) {ps. setString (1, "haohan" + I); ps. setString (2, "robbery"); ps. setInt (3, 0); ps. setDate (4, null); ps. setDouble (5, 1000.0); ps. setDouble (6, 8000.0); ps. setInt (7, 3); // store the data in ps. addBatch (); // send data in batches once every 30 times if (I % 30 = 0) {ps.exe cuteBatch (); // clear the cached data ps. clearBatch () ;}}// the remaining data is sent separately by ps.exe cuteBatch (); conn. commit ();} catch (SQLException e) {try {conn. rollback ();} catch (SQLException e1) {e1.printStackTrace ();} e. printStackTrace (); throw new RuntimeException ("batch add employee failed", e);} finally {DBUtil. close (conn );}}

This is an example of batch insert of employees. The first thing to note is that SQL statements are sent in batches only if their SQL statements are the same, before starting batch processing, you must set the transaction settings to manual submission. The next step is to create an SQL variable parameter model. For example, I have created an insert model, the for loop below is designed to save time and write 108 pieces of data into it. Of course, you can also write them one by one.

Next I will explain the addBatch () method. We did not write 108 pieces of data directly to the database. It also called the ParperdStatement sending method, however, this is not excuteQuery. The written content must be put into the cache first, then some data is obtained from the cache and sent to the database, and the sent SQL statement is cleared from the cache, the following code is sent every 30 times. Call excuteBatch to send the code and then call clearBatch to clear the cache. Of course, the rest of the Code must be sent once again by calling excuteBatch. Do not forget to submit the code, because it has been set to manual submission.

3. An Automatic Primary Key is returned.

First of all, I think this is not very easy to understand, and it seems that it is not as simple as above. Next I will also introduce an example to illustrate it:

This example looks like this. First, there must be two tables, one is the department table and the other is the employee table. These two tables are associated, that is, the primary key deptno of the Department table in the master table also appears in the columns of the slave table and becomes the foreign key of the slave table. When the master table is inserted, inserts information from the table.

1 @ Test 2 public void test4 () {3 // assume that the Department data to be added is as follows 4 String dname = "Finance Department"; 5 String loc = "Beijing "; 6 // assume that the data of the employee to be added is as follows: 7 String ename = "zhangsan"; 8 String job = "manager"; 9 int mgr = 0; 10 double sal = 8000.0; 11 double comm = 2000.0; 12 13 String ename2 = ""; 14 String job2 = "manager"; 15 int mgr2 = 0; 16 double sal2 = 5000.0; 17 double comm2 = 500.0; 18 19 Connection conn = null; 20 try {21 conn = DBUtil. getConnection (); 22 conn. setAutoCommit (false); 2 3 // Add Department 24 String SQL = "insert into depts_jiawen" 25 + "values (depts_seq_jiawen.nextval ,?,?) "; 26 // parameter 2 is an array that stores the field name to be remembered by ps 27 PreparedStatement ps = conn. prepareStatement (SQL, new String [] {"deptno"}); 28 ps. setString (1, dname); 29 ps. setString (2, loc); 30 ps.exe cuteUpdate (); 31 32 // obtain the previously recorded field value from ps 33 // only one type of data is returned in the returned result set 34 // the value of those fields is recorded 35 ResultSet rs = ps. getGeneratedKeys (); 36 rs. next (); 37 int deptno = rs. getInt (1); 38 39 // Add employee 40 SQL = "insert into emp_jiawenzhe values (" 41 + "depts_seq_jiawen.nextval, ?,?,?,?,?,?,?) "; 42 ps = conn. prepareStatement (SQL); 43 ps. setString (1, ename); 44 ps. setString (2, job); 45 ps. setInt (3, mgr); 46 ps. setDate (4, null); 47 ps. setDouble (5, sal); 48 ps. setDouble (6, comm); 49 ps. setInt (7, deptno); 50 ps.exe cuteUpdate (); 51 52 ps = conn. prepareStatement (SQL); 53 ps. setString (1, ename2); 54 ps. setString (2, job2); 55 ps. setInt (3, mgr2); 56 ps. setDate (4, null); 57 ps. setDouble (5, sal2); 58 ps. setDouble (6, comm2); 59 ps. setInt (7, deptno); 60 ps.exe cuteUpdate (); 61 62 conn. commit (); 63 64} catch (SQLException e) {65 try {66 conn. rollback (); 67} catch (SQLException e1) {68 // TODO Auto-generated catch block69 e1.printStackTrace (); 70} 71 e. printStackTrace (); 72 throw new RuntimeException ("wrong", e); 73} finally {74 DBUtil. close (conn); 75} 76}

Here we can see that ParperdStatement has passed in two parameters. The first is the same as before, and the second is a string array, it is the field name that you want to remember. In my understanding, the foreign key field is put in it. In order to get the value of this foreign key later, it is passed in to the slave table for update, then call getGeneratedKeys () to obtain the result set of these primary keys, and then use int deptno = rs. getInt (1); to get the value of the corresponding field, I can't explain it clearly. At present, I can only say that first remember it, the insert slave table is a batch processing operation, which is the same as the above.

4. Paging

Pagination means that a larger data table can be divided into several segments when we do not want to see the whole table. This content is a fixed mode with a fixed paging formula, which is clear at a glance, you can use it directly when using it.

Sample Code:

 1     @Test 2     public void test5(){ 3         int size=10; 4         int page=2; 5          6         Connection conn=null; 7         try { 8             conn=DBUtil.getConnection(); 9             String sql="select * from( "10                     + "select e.*,rownum r from ( "11                     + "select * from emp_jiawenzhe "12                     + "order by empno "13                     + ") e "14                     + ") where r between ? and ?";15             PreparedStatement ps=conn.prepareStatement(sql);16             ps.setInt(1, (page-1)*size+1);17             ps.setInt(2, size*page);18             ResultSet rs=ps.executeQuery();19             while (rs.next()) {20                 System.out.println(rs.getInt("empno")+","+rs.getString("ename"));21                 22             }23         } catch (SQLException e) {24         25             e.printStackTrace();26             throw new RuntimeException("wrong",e);27         }finally{28             DBUtil.close(conn);29         }30     }

Page and size are divided into several pages, each of which has several pages. The paging SQL statement is written in the database content. I will mention it in the basic SQL usage of the database, the following content is clear!

Not complete to be continued!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.