当前位置:网站首页>Dbutil auxiliary class, manual commit transaction, metadata
Dbutil auxiliary class, manual commit transaction, metadata
2022-06-11 12:58:00 【The joy of looking up at the stars】
Apache dbutil There are many classes in this package , Mainly the following three
- Dbutils auxiliary
- Queryrunner: Additions and deletions , If the data is submitted to the database automatically , You must implement a constructor with parameters
Update()
Query()
- If it's a query , Need to use resultsetHandler Interface , There are many implementation classes , An implementation class corresponds to a different query type
( Corresponding to different return value types )
QueryRunner runner=new QueryRunner(getdatasourceClass.getdatasourceFunction());
ArrayHandler Return the first row of data in the result set , And use object Array receive
Object[] student=runner.query("select * from student_info where id>?",new ArrayHandler(),1);
System.out.print(student[1]);
ArrayListHandler With list And an array to return the result set ,list There is one in every line of the object Array
List<Object[]> students=runner.query("select * from student_info where id>?",new ArrayListHandler(),1);
for(Object[] student:students)
{System.out.print(student[0]);}
BeanHandler Returns the first row of data in the result set as a class , Note that the variable name in the class should be consistent with the table
Student student=runner.query("select * from student_info where id>?",new BeanHandler <Student> (Student.class),1);//Student.class yes java Reflection of , Don't understand, , Write this to automatically put the query results in student In the object
System.out.print(student.getLoc());
BeanListHandler Return multiple rows of data in the result set with list<student> receive
List<Student> students=new ArrayList<>();
students=runner.query("select * from student_info where id>?",new BeanListHandler<Student>(Student.class),1);
BeanMapHandler Number the result set , return map oracle The default data type in is decimal type ,java neutralization decimal The corresponding is bigdecimal type
Map<BigDecimal,Student> students=runner.query("select * from student_info where id>?",newBeanMapHandler<BigDecimal,Student>(Student.class,"id"),1);
Student stu=students.get( new BigDecimal(1));
MapHandler With map Returns the first row of query results in
Map<String,Object> student =runner.query("select * from student_info where id>?",new MapHandler(),1);
System.out.print(student);//
result :{ID=2, NAME=name2, PWD=pwd2, LOC=loc2}
<String,Object> It's a rule to put this map The format of ,key yes string,value yes object
MapListHandler Return multiple rows of results in the result set
List< Map<String,Object>> student =runner.query("select * from student_info where id>?",new MapListHandler(),1);
System.out.print(student);
result :[{ID=2, NAME=name2, PWD=pwd2, LOC=loc2}, {ID=5, NAME=name5, PWD=loc5, LOC=psw5}]
List Put in map
Columnlisthander: Put a column in the result ( Like all of them id), Save in list
List< String> student =runner.query("select * from student_info where id>?",new ColumnListHandler<String>("loc"),1);
System.out.print(student);
among object…paramas Represents a variable parameter : You can write a single value , You can also write arrays
Object[] student=runner.query("select * from student_info where id>? And name like ?",new ArrayHandler(),new Object[]{ 1,"%n%"});
System.out.print(student[0]);
Maybe because jar Package version problem , When the parameter is an array ( The above sentence ) Perform error , Just change another version
increase ( Auto commit transaction )
int result= runner.update(" insert into student_info values(?,?,?,?)",new Object [ ] { 6,"name6","loc6","psw6"} );
System.out.print(result);
Delete ( Auto commit transaction )
int result= runner.update(" delete from student_info where id=?",2 );
System.out.print(result);

Commit transactions manually :
Transfer accounts , There should be two steps , First reduce Zhang San's money , Give Li Si more money . Or at the same time , Or fail at the same time .
step :
If you want to ensure data security , But also to ensure performance , have access to threadlocal
Connection Can not be further divided , One connection Only one addition, deletion, modification and query can be completed , And when it's done, submit , But I need to add, delete, modify and check many times , Submit again , You use threadlocal, At the first dao In operation Really created a connection object , Then several other times dao In operation , With the help of t1 Its own characteristics The connection Duplicate multiple (connection Only one... Was created , So it's time to connection All operations in Must correspond to the same transaction ) also t1 take connection Multiple... Are copied at the use level , Therefore, multiple... Can be completed at the same time dao operation , Submit only once .
Threadlocal: Make a copy for each thread , Each thread can access its own internal copy , Alias thread local variable
Set() to t1 Store a variable in
Get() from t1 Get variables in ( copy )
Remove() Delete copy
For databases , One connection corresponds to one transaction , A transaction can contain multiple dml operation ( Additions and deletions )
All objects . Methods need to judge whether they are empty
Transaction flow : Open transaction ( Changing automatic commit to manual commit is to start the transaction )
Carry on all kinds of dml operation normal Will just all dml Submit all
Failure ( abnormal ) Will just all dml Roll back all ( All failed )
Metadata : Data that describes data
Three types of : Database metadata 、 Parameter metadata 、 ResultSet Metadata
- Database metadata DataBaseMetaData
Database metadata includes Database name Database version information Driver name url user name
Just remember that Connection ->databasemetadata->. The acquisition method of database metadata can
Connection conn= getdatasourceClass.getdatasourceFunction().getConnection();
DatabaseMetaData dbmetadata =conn.getMetaData();
String dbname=dbmetadata.getDatabaseProductName();// Returns the database name
System.out.println(dbname);
String username=dbmetadata.getUserName();// Get username
System.out.println(username);
String dbversion=dbmetadata.getDatabaseProductVersion();// Get the version information of the database
System.out.println(dbversion);
String drivername=dbmetadata.getDriverName();// Get driver name
System.out.println(drivername);
Specify the primary key information of the table getprimarykeys()
ResultSet rs=dbmetadata.getPrimaryKeys(null,username,"STUDENT_INFO");
// The first parameter is category information , Usually it is null If the second one is oracle database , Capitalized user name , The third is the upper case table name
while (rs.next())
{
Object tablename=rs.getObject(1);// Table category
Object tablename=rs.getObject(2);// Table mode
Object tablename=rs.getObject(3);// The name of the table
Object columnname=rs.getObject(4);// Primary key name
Object columnname=rs.getObject(5);// The serial number of the primary key
Object columnname=rs.getObject(6);// Constraint name of primary key
}
- Parameter metadata
Connection conn= getdatasourceClass.getdatasourceFunction().getConnection();
PreparedStatement pstat=conn.prepareStatement("select * from student_info where id>?",0);
ParameterMetaData prematacount= pstat.getParameterMetaData();
int count=prematacount.getParameterCount();
System.out.println(count);
Just remember that connection-》 Pstat-》 parameterMeatadata-》. The acquisition method of
- ResultSet Metadata resultsetmeatadta
Just remember that Resultset->resultsetmetadata
Connection conn= getdatasourceClass.getdatasourceFunction().getConnection();
PreparedStatement pstat=conn.prepareStatement("select * from student_info ");
ResultSet rs= pstat.executeQuery();
ResultSetMetaData data= rs.getMetaData();
System.out.println(data.getColumnCount());// The returned result set has several columns ( There are several properties )
System.out.println(data.getColumnName (i));// Return result set No i Column name
System.out.println(data.getColumnTypeName (i));// Return result set No i The type of the column
边栏推荐
- Unity game protection "big training", read and understand the game's pre defense
- 【增加功能】select下拉多选 显示选中的人员
- 2022 vmvare download and installation tutorial on the latest official website (ultra detailed)
- oracle数据库导入数据步骤
- 2020.10.27 summary of Beijing Ali cultural and entertainment
- ProblemB. Phoenix and Beauty
- Is it safe to open an account online in 2022?
- Deep learning and CV tutorial (14) | image segmentation (FCN, segnet, u-net, pspnet, deeplab, refinenet)
- Simple score statistics
- [clearos] install the clearos system
猜你喜欢

PADS使用之绘制原理图

石头科技:研发实力和过硬品质 助力扫地机器人产业升级

综合场馆的优势有哪些?

历史上的今天:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生...

【bug解决】表单分页,显示总数据res.data.total

PADS使用之繪制原理圖

Which brand of bone conduction Bluetooth headset is good? Five most popular bone conduction Bluetooth headsets

Netstat command details

Stone technology: R & D strength and excellent quality help upgrade the sweeping robot industry

. 5 string
随机推荐
Redis data type Daily use Scenarios
一个时代的终结!十年了吴恩达经典《机器学习》课程本月关闭注册,上线新课!...
科海融生&正航,以信息化驱动管理升级,携手共迎数智未来
Ways to double the summer performance of natatoriums
DB2数据库重建及表数据迁移探讨研究
Seckill multi-level cache ----- product details page
【滤波器】基于matlab时变维纳滤波器设计【含Matlab源码 1870期】
App manual signature of openharmony standard system
.net core 抛异常对性能影响的求证之路
Unity 游戏保护“大练兵”,一文读懂游戏事前防御
31w赛题奖金!当 AI for Science 撞上“先导杯”,会擦出什么样的火花?
Usage of instr function in Oracle Database
工作总结之因为笛卡尔积问题写SQL搞了半天[害](附笛卡尔积总结)
【backtrader源码解析46】cerebro.py代码注释(枯燥,backtrader核心代码之一,推荐阅读,注释仅供参考)
知物由学 | 行为时序建模在社交引流黑产识别中的应用
启封easy QF PDA帮助企业提升ERP的管理水平
Which 4K projector is the most cost-effective? When the Bay X3 Pro highlights the 128G storage 618, it is worth seeing
pip2pi和pypiserver及Apache在pip本地源配置中的应用实践
What are the advantages of comprehensive venues?
How can mechanical equipment manufacturing enterprises manage outsourcing with the help of ERP system?