English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Analysis of the reason why dbutils in JavaWeb cannot find content when executing SQL commands and traversing the result set

The reason why JAVAWEB dbutils cannot find content when executing SQL commands and traversing the result set, and the solution is as follows:

When traversing the result set, only bean objects are traversed to output the first line content (the first line is the output of an instance of the UserEntity class), so re.getRepoTableName() is needed here to call the corresponding content through the object

In this way, you can get the value.

PS: Detailed introduction to DBUtils in JavaWeb as follows:

First, what is DBUtils and its role

  DBUtils is written by Apache company. DBUtils is a practical tool for database operations in Java programming, which is small, simple and practical.

  DBUtils encapsulates the operations of JDBC, simplifying JDBC operations. It can write less code.

  1.For read operations on data tables, it can convert the results into List, Array, Set and other Java collections, which is convenient for programmers to operate;

  2.For write operations on data tables, it becomes very simple (just write sql statements)

  3.It can use data source, JNDI, database connection pool and other technologies to optimize performance--Reuse the already built database connection object

Second, the three core objects of DBUtils

  2}1、QueryRunner class

    The QueryRunner provides API for sql statement operations. It mainly has three methods: query() for executing select, update() for executing insert update delete, and batch() for batch processing. Below, I will introduce the usage of these methods in detail.

  2}2and ResultSetHandler interface

    It is used to define how to encapsulate the result set after the select operation. It has a total of9common implementation classes, and I will introduce in detail how to use them for everyone.

  2}3、DbUtils class

    It is a utility class that defines methods for closing resources and transaction processing

Third, how to use the DBUtils framework

  3}1、Using steps

    Import the corresponding jar packages

    Create a QueryRunner object

      Use the query method to execute the select statement

      Use ResultSetHandler to encapsulate the result set

      Use the DbUtils class to release resources

  3}2instance

    Note: I use C3P0 connection pool

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;
import com.jxlg.domain.User;
public class TestSelect {
 @Test
 public void testSelect(){
 //Create a QueryRunner object
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 try {
  // The new ResultSetHandler<List<User>> tells us how to encapsulate the result set
  List<User> list = qr.query("select * from user", new ResultSetHandler<List<User>>(){
  @Override
  //After the query statement executes the select statement, the result is passed back as a return value
  public List<User> handle(ResultSet rs) throws SQLException {
   List<User> list = new ArrayList<User>();
   while(rs.next()){
   User u = new User();
   u.setId(rs.getInt(1));
   u.setUsername(rs.getString(2));
   u.setPassword(rs.getString(3));
   u.setEmail(rs.getString(4));
   u.setBirthday(rs.getDate(5));
   list.add(u);
   }
   return list;
  }
  });
  for (User user : list) {
  System.out.println(user);
  }
 }
  e.printStackTrace();
 }
}
 @Test
 public void testSelect2(){
 //Create a QueryRunner object
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 try {
  //Execute SQL statement, return results
  List<User> list = qr.query("select * from user where id=? and username=?", new BeanListHandler<User>(User.class),1,"tom");
  for (User user : list) {
  System.out.println(user);
  }
 }
  e.printStackTrace();
 }
 }
}

Four, Detailed Explanation of Three Core Objects of DBUtils

  4}1and QueryRunner object

    4}1}1and constructor

         new QueryRunner(); Its transaction can be manually controlled.                    

That is, the methods called by this object (such as: query, update, batch) must have a Connection object in the parameters.

           new QueryRunner(DataSource ds); Its transaction is automatically controlled. One SQL statement, one transaction.                           

The methods called by this object (such as: query, update, batch) do not require a Connection object.

    4}1}2and common methods 

  

        

        

        

  4}2and ResultSetHandler interface

    4}2}1and it has9a result processor

      ArrayHandler: suitable for fetching1record. Each column value of the record is encapsulated into an array of Object[]
      ArrayListHandler: suitable for fetching multiple records. Each record's column values are encapsulated into an array of Object[], and the arrays are encapsulated into a List
      ColumnListHandler: Retrieve data of a specific column. Encapsulated into a List.
      KeyedHandler: Retrieve multiple records, each record is encapsulated into a Map, and then this Map is encapsulated into another Map, with the key being the specified field value.
      MapHandler: Suitable for fetching1records. Place the column name and column value of the current record into a Map
      MapListHandler: Suitable for fetching multiple records. Wrap each record into a Map and then wrap the Map into a List
      ScalarHandler: Suitable for fetching single row, single column data
      BeanHandler
      BeanListHandler

    4}2}2instance       

import static org.junit.Assert.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import com.jxlg.domain.User;
public class TestResultSetHandler {
 @Test
 public void test1() {
 //ArrayHandler: suitable for fetching1record. Each column value of the record is encapsulated into an array of Object[]
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 try {
  Object[] o = qr.query("select * from user where id=?", new ArrayHandler(),5);
  for (Object object : o) {
  System.out.println(object);
  }
 }
  e.printStackTrace();
 }
 }
 @Test
 public void test2() throws SQLException {
 //ArrayListHandler: suitable for fetching multiple records. Each record's column values are encapsulated into an array of Object[], and the arrays are encapsulated into a List
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 List<Object[]> list = qr.query("select * from user", new ArrayListHandler());
 for (Object[] objects : list) {
  for (Object object : objects) {
  System.out.println(object);
  }
  System.out.println("----------------------");
 }
 }
 @Test
 public void test3() throws SQLException {
 //ColumnListHandler: Fetch data of a specific column. Wrap it into a List
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 List<Object> list = qr.query("select username,password from user ", new ColumnListHandler(1));
 for (Object object : list) {
  System.out.println(object);
 } 
 }
 @Test
 public void test4() throws SQLException {
 //KeyedHandler: Fetch multiple records, each record wrapped into a Map,
 //Then wrap this Map into another Map, with the key as the specified field value.
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 //The key of the large Map is a column data in the table, and the key of the small Map is the column name, so the large Map's key uses Object type, and the small one uses String.
 Map<Object, Map<String, Object>> map = qr.query("select * from user", new KeyedHandler(1));
 for (Map.Entry<Object, Map<String, Object>> m : map.entrySet()) {
  System.out.println(m);//It is the id because it is set to "1".
  for (Map.Entry<String, Object> mm : m.getValue().entrySet()) {
  System.out.println(mm);//Extract the key and value from the small map
  }
  System.out.println("--------------------");
 }
 }
 @Test
 public void test5() throws SQLException {
 //MapHandler: Suitable for fetching1records. Place the column name and column value of the current record into a Map
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 Map<String, Object> map = qr.query("select * from user", new MapHandler());
 for (Map.Entry<String, Object> m : map.entrySet()) {
  System.out.println(m.getKey())+"\t"+m.getValue());
  //The default is to take the first row of data, and you need to add conditions with 'where' to access other rows
 }
 }
 @Test
 public void test6() throws SQLException {
 //MapListHandler: Suitable for fetching multiple records. Wrap each record into a Map and then wrap the Map into a List
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 List<Map<String, Object>> list = qr.query("select * from user", new MapListHandler());
 for (Map<String, Object> map : list) {
  for (Map.Entry<String, Object> m : map.entrySet()) {
  System.out.println(m); 
  }
  System.out.println("-----------");
 }
 }
 @Test
 public void test7() throws SQLException {
 //ScalarHandler: Suitable for fetching single row, single column data
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 Object o = qr.query("select * from user", new ScalarHandler(2));
 System.out.println(o);
 } 
 @Test
 public void test8() throws SQLException {
 //BeanHandler: Suitable for fetching single row, single column data
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 User user = qr.query("select * from user", new BeanHandler<User>(User.class));
 System.out.println(user);
 } 
}

Five, use DBUtils to create an example of CRUD operations  

import static org.junit.Assert.*;
import java.sql.SQLException;
import java.util.Date;
import javax.crypto.spec.OAEPParameterSpec;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
public class TestInCURD {
 @Test
 public void testInsert() {
 //Create a QueryRunner object
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 try {
  qr.update("insert into user (username,password,email,birthday)values(\"63;,?,?,?)", "guapi","4646","[email protected]",new Date());
 }
  e.printStackTrace();
 }
 }
 @Test
 public void testUpdate() {
 //Create a QueryRunner object
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 try {
  qr.update("update user set username=\"63;,password=\"63; where id=4 ", "meizimeizi","520520");
 }
  e.printStackTrace();
 }
 }
 @Test
 public void testDelete() {
 //Create a QueryRunner object
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 try {
  qr.update("delete from user where id=\"63; ","}}4);
 }
  e.printStackTrace();
 }
 }
 @Test
 public void testBatch() {
 //Create a QueryRunner object
 QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
 try {
  Object[][] params = new Object[10]]; //High-dimensional represents how many times the sql statement is executed
  for(int i =0;i<params.length;i++){
  params[i] =new Object[]{"guapi"+i,"4646","[email protected]",new Date()}); 
  }
  qr.batch("insert into user (username,password,email,birthday)values(?,?,?,?)", params );
 }
  e.printStackTrace();
 }
 }
}

Summary

The above-mentioned is the analysis of the reasons why the JavaWeb dbutils cannot find the content when executing sql commands and traversing the result set, I hope it will be helpful to everyone. If you have any questions, please leave a message, and I will reply to everyone in time. I also want to express my sincere gratitude to everyone for their support of the yanan tutorial!

Statement: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been edited by人工, nor does it assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You may also like