current position:Home>JDBC ~ resultset, use of resultsetmetadata, ORM idea, arbitrary field query of any table (JDBC Implementation)
JDBC ~ resultset, use of resultsetmetadata, ORM idea, arbitrary field query of any table (JDBC Implementation)
2022-05-15 07:30:14【Salute-Y】
List of articles
ORM thought
- ORM Mapping thought (Object relational mapping)
- One data table corresponds to one Java class
- A record in the table corresponds to Java An object of class
- A field in the table corresponds to java An attribute of a class
ResultSet、ResultSetMetaData Use
ResultSet
- PreparedStatement Of executeQuery Method returns a resultSet object
- Return a piece of data in the form of a table
- It comes with a pointer to the first field of data ,next Method can control this pointer
- The first field subscript defaults to 1
ResultSetMetaData
- You can get the type of column and other information
- adopt ResultSet Of getMetaData() Methods to get
- Relationship between them
utilize JDBC Implement query operation
- Query is different from addition, deletion and modification , The addition, deletion and modification did not return , Only the records in the database have been modified , And the query has a return value , How to deal with the return value is the problem
- JDBC of use executeQuery Method handles the return value , And return a resultSet Result set
- The key point of query operation is the processing of result set
public static void testQuery() throws Exception{
Connection connection=JDBCUtils.getConnection();
String sql="select id,name,balance from account where id=?";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setInt(1,1);
// perform , And return the result set
ResultSet resultSet=statement.executeQuery();
// Processing result set
if(resultSet.next()){
//next Method : Judge whether there is data in the next item , There's data coming back true, And move the pointer down , If there is no data , Just go back to false, The pointer no longer moves down
// Get the field values of the current data
int id=resultSet.getInt(1);
String name=resultSet.getString(2);
Double balance=resultSet.getDouble(3);
// Mode one : System.out.println("id="+id+...);
// Mode two : Object[] objects=new Object[]{id,name,balance};
// Mode three : Encapsulating data as an object
Table table= new Table(id,name,balance);
System.out.println(table);
}
// close resource
JDBCUtils.closeResource(connection,statement);
resultSet.close();
}
utilize JDBC Realize the query of any field of a table
public static Table testQueryBetter(String sql,Object...args)throws Exception{
Connection connection=JDBCUtils.getConnection();
PreparedStatement statement=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
statement.setObject(i+1,args[i]);
}
ResultSet resultSet=statement.executeQuery();
// Get metadata of result set :ResultSetMetaData
ResultSetMetaData rsmd=resultSet.getMetaData();
// Get the number of columns through the metadata of the result set
int columnCount=rsmd.getColumnCount();
if(resultSet.next()){
Table table=new Table();
for(int i=0;i<columnCount;i++){
Object value=resultSet.getObject(i+1);
// Get the column name of each column
String columnName=rsmd.getColumnLaber(i+1);
// to table The specified attribute of the object is copied as value, By reflection
Field field=Table.class.getDeclaredField(columnName);
field.setAccessible(true);
field.set(table,value);
}
return table;
}
// close resource
JDBCUtils.closeResource(connection,statement);
resultSet.close();
return null;
}
- If the field name of the table is different from the attribute name of the class , You can use the property name of the class as an alias for the field , Add... When querying
- Get the alias of the column of the table :getColumnLabel Method , When there is no alias, it is the original name
- Connection to database Connection It's a rare resource , When used up, it must be released , The system may crash if it is not released
Query process
utilize JDBC Realize the query of any field of any table
public static <T> T testQueryTable(Class<T> clazz,String sql,Object...args)throws Exception{
Connection connection=JDBCUtils.getConnection();
PreparedStatement ps=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
ResultSet resultSet=ps.executeQuery();
ResultSetMetaData rsmd=resultSet.getMetaData();
// To get the column name
int columCount=rsmd.getColumnCount();
// Processing result set
if(resultSet.next()){
T t = clazz.newInstance();
// Process each column of this record
for(int i=0;i<columCount;i++){
Object value=resultSet.getObject(i+1);
// To get the column name , And set it to the specified object attribute through the column name , By reflection
String columnLabel=rsmd.getColumnLabel(i+1);
Field field=clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,value);
}
return t;
}
// close resource
JDBCUtils.closeResource(connection,ps);
resultSet.close();
return null;
}
summary
- JDBC There are two ideas when using : Interface oriented programming and ORM thought
- Interface oriented programming is oriented to JDBC API , Not involving other third-party databases API
- ORM The idea is to return the result as an object when processing the result set ( Use string or Object Arrays are also ok)
- JDBC There are two programming techniques involved :
- ResultSetMateData Get the number of columns and alias in :getColumnCount、getColumnLabel
- Process the result with reflection , Specify the class and assign a value
copyright notice
author[Salute-Y],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/135/202205142334279285.html
The sidebar is recommended
- Single cell column - how to give orig Ident, change your name
- Fonts best practices
- Wonderful express | April issue of Tencent cloud database
- Illustration: what is the difference between layer 2 and layer 3 switches?
- Activity Notice | timing adjustment of 2022 deterministic network technology and Innovation Summit
- In order to seize the capacity of 5nm chips, AMD will pay an advance payment of US $6.5 billion to TSMC, grofangde and other suppliers; Germany will adopt stricter antitrust rules for Google meta
- It is reported that TSMC will promote the 1.4 nm process next month; Taobaoyuan universe trademark rejected
- Online binary 8-hexadecimal conversion tool
- [paper notes] epsanet: an efficient pyramid sequence attention block on revolutionary neural network
- IndexError: shape mismatch: indexing tensors could not be broadcast together with shapes [2], [3]
guess what you like
What are the development stages of time series database in recent years?
What are the shortcomings of the data model processed in the first stage of time series database?
What are the shortcomings of the data model processed in the second stage of time series database?
What are the development trends of time series database?
What are the characteristics of cloud native multimode database lindorm?
What are the functions of cloud native multimode database lindorm?
Variance, standard deviation, mathematical expectation
Two dimensional Gaussian distribution
Collaborative process and channels (CSP: kotlin, golang)
SQLite3 custom function (UDF)
Random recommended
- SQLite3 minimalist Tutorial & go operating data structures using SQLite memory mode
- Penetration test - DNS rebinding
- The pytoch loading model only imports some layer weights, that is, it skips the method of specifying the network layer
- Parameter and buffer in pytoch model
- torch. nn. functional. Interpolate function
- Specify the graphics card during pytorch training
- [paper notes] Dr TANet: dynamic receptive temporary attention network for street scene change detection
- [MQ] achieve mq-08- configuration optimization from scratch fluent
- New signs are taking place in the Internet industry, and a new transformation has begun
- ACL 2022 | visual language pre training for multimodal attribute level emotion analysis
- Cvpr2022 | latest progress in small sample behavior recognition strm framework, spatio-temporal relationship modeling is still the top priority
- Hallucinations in large models
- Is it safe to open an account online? Which of the top ten securities companies are state-owned enterprises?
- [encapsulation tips] encapsulation of list processing function
- Start with Google sea entrepreneurship accelerator - recruitment and start
- Hard core preview in May! Lecture tomorrow night: virtio virtualization technology trend and DPU practice | issue 16
- Druid source code reading 1 - get connection and release connection
- Graduation summary of actual combat training camp
- Public offering "imported products" temporarily hit the reef? The first foreign-funded public offering BlackRock fund has a lot of bad thoughts or a lot of things. It is acclimatized and the performance of the two products is poor
- Introduction and installation of selenium module, use of coding platform, use of XPath, use of selenium to crawl JD product information, and introduction and installation of sketch framework
- Financial IT architecture - Analysis of cloud native architecture of digital bank
- [paper notes] lsnet: extreme light weight Siamese network for change detection in remote sensing image
- Mock tool equivalent to Fiddler!
- Write a program, input several integers (separated by commas) and count the number of occurrences of each integer.
- Inventory a voice conversion library
- Technology selection of micro service registration center: which of the five mainstream registration centers is the most popular?
- Summary of root cause analysis ideas and methods | ensuring it system and its stability
- JS custom string trim method
- Web3: the golden age of Creator economy
- Introduction and installation of selenium module, use of coding platform, use of XPath, use of selenium to crawl JD product information, and introduction and installation of sketch framework
- Basics: a 5-makefile example
- Database connection pool Druid source code learning (V)
- Check the box to prevent bubbling
- Click on the box to change color
- Local style and global style of uniapp
- LeetCode. 2233. Maximum product after K increases (math / minimum heap)
- Overview, BGP as, BGP neighbor, BGP update source, BGP TTL, BGP routing table, BGP synchronization
- Routing policy and routing control
- Principle and configuration of IS-IS
- Basic operation of linked list (complete code)