当前位置:网站首页>Metadata of database
Metadata of database
2022-06-27 10:29:00 【Everything will always return to plain】
Catalog
1.2 The role of database metadata
2.2 Obtain comprehensive information of the database
2.4 Get all the table information in a database
2.5 Get the field properties in the specified database table
3.1 Get precompiled SQL The number of placeholder parameters in the statement
1、 Metadata in the database
1.1 What is database metadata
Metadata (MetaData), It refers to the data that defines the data structure .
For example, the header of this table ( Name )

Of course, there are database names and table names .

In addition to these, there are user names 、 Version name and from SQL Most of the strings in the result of the statement are metadata .
1.2 The role of database metadata
What is the role of metadata in the database ?
There are two main aspects :
- Application design , For example, code generator , It requires database metadata .
- If you know database metadata , You can have a deeper understanding of some frameworks of the database , for example jpa,Mybatis.
1.3 How to get metadata
We are JAVA Operation database , does JDBC, Whether it's MySQL still Oracle Or other databases , Basically through JDBC To deal with the database .
Use JDBC There are three main interfaces to handle databases , namely Connection,PreparedStatement and ResultSet These three interfaces .
For these three interfaces , You can also get different types of metadata .
Interface | explain |
Connection | Get database metadata (DatabaseMetaData) |
PreparedStatement | Get the parameter metadata we get by sending the request (ParameterMetaData) |
ResultSet | Get result set metadata (ResultSetMetaData) |
The following will introduce the three types of metadata objects respectively and use MYSQL Database for case description .
2、 Database metadata
Database metadata (DatabaseMetaData): By Connection Object passing getMetaData Method , It mainly encapsulates some overall comprehensive information about the database itself , For example, the name of the database , Version number of the database , Database URL, Whether transactions are supported .
Here are some about DatabaseMetaData The common method of :
Method | explain |
getDatabaseProductName | Get the name of the database |
getDatabaseProductName | Get the version number of the database |
getUserName | Get the user name of the database |
getURL | Get the database connection URL |
getDriverName | Get the driver name of the database |
driverVersion | Get the driver version number of the database |
isReadOnly | Check whether the database only allows read operations |
supportsTransactions | Check whether the database supports transactions |
2.1 Constructing environment
I just picked up one that I used to do Demo Of project (SpringBoot project ) To write .
Introduced mySql rely on .
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>Since it is SpringBoot project , That is, of course, direct use yml file Configure the database connection .
server:
port: 80
spring:
application:
name: mp
datasource: # Configure data source information
url: jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
username: root
password: 1234
driver-class-name: com.mysql.cj.jdbc.Driver2.2 Obtain comprehensive information of the database
@SpringBootTest
class MetadataTest {
// data source
@Resource
DataSource dataSourcee;
@Test
void Test01() {
try {
// Get database metadata
DatabaseMetaData dbMetaData = dataSourcee.getConnection().getMetaData();
// Get database product name
String productName = dbMetaData.getDatabaseProductName();
System.out.println(" Database product name :" + productName);
// Get the database version number
String productVersion = dbMetaData.getDatabaseProductVersion();
System.out.println(" Database version number :"+productVersion);
// Get the database user name
String userName = dbMetaData.getUserName();
System.out.println(" Database user name :"+userName);
} catch (Exception throwables) {
throwables.printStackTrace();
}
}
} Here are three , It's all the same anyway , The rest of us try it by ourselves .
effect :

2.3 Get the database list
@SpringBootTest
class MetadataTest {
// data source
@Resource
DataSource dataSourcee;
@Test
void Test01() {
try {
// Get database metadata
DatabaseMetaData dbMetaData = dataSourcee.getConnection().getMetaData();
// Get the database list
ResultSet rs = dbMetaData.getCatalogs();
// Traverse to get all database tables
while (rs.next()) {
// Print database name
System.out.println(" Table name :"+rs.getString(1));
}
// Release resources
rs.close();
dataSourcee.getConnection().close();
} catch (Exception throwables) {
throwables.printStackTrace();
}
}
2.4 Get all the table information in a database
@Test
void Test01() {
try {
// Get database metadata
DatabaseMetaData dbMetaData = dataSourcee.getConnection().getMetaData();
// Get the specified table information in the specified database
ResultSet tablers = dbMetaData.getTables(null, null, "t_user", new String[]{"TABLE"});
// assemble table
while (tablers.next()) {
// Database 1 || TABLE_CAT
System.out.println(" Database :" + tablers.getString("TABLE_CAT"));
// Table mode 2 || TABLE_SCHEM
System.out.println(" Table mode :" + tablers.getString("TABLE_SCHEM"));
// Table name 3 || TABLE_NAME
System.out.println(" Table name :" + tablers.getString("TABLE_NAME"));
// Database table type 4 || TABLE_TYPE
System.out.println(" type :" + tablers.getString("TABLE_TYPE"));
// Database table remarks 5 || REMARKS
System.out.println(" remarks :" + tablers.getString("REMARKS"));
}
} catch (Exception throwables) {
throwables.printStackTrace();
}
}The method of obtaining table data getTables Medium 4 The parameters are :
Parameters | explain |
catalog | Database name ,null All databases |
schemaPattern | Schema name , stay mysql There is no special significance in , So fill it directly null . |
tableNamePattern | Table name ,null Is all the tables |
types[] | type : TABLE: surface VIEW: View |
Let's see the implementation effect :

2.5 Get the field properties in the specified database table
@Test
void Test01() {
try {
// Get database metadata
DatabaseMetaData dbMetaData = dataSourcee.getConnection().getMetaData();
// Get the field information in the specified database table
ResultSet columns = dbMetaData.getColumns("mybatis_plus", null, "t_user", null);
// assemble table
while (columns.next()) {
// Database 1 || TABLE_CAT
System.out.println(" Database :" + columns.getString("TABLE_CAT"));
// Table mode 2 || TABLE_SCHEM
System.out.println(" Table mode :" + columns.getString("TABLE_SCHEM"));
// Table name 3 || TABLE_NAME
System.out.println(" Table name :" + columns.getString("TABLE_NAME"));
// Name 4 || COLUMN_NAME
System.out.println(" Name :" + columns.getString("COLUMN_NAME"));
// Database table type 5 || DATA_TYPE
System.out.println(" type :" + columns.getString("DATA_TYPE"));
// Database table remarks 12 || REMARKS
System.out.println(" remarks :" + columns.getString("REMARKS"));
}
} catch (Exception throwables) {
throwables.printStackTrace();
}
}This has not changed much , Just another way getColumns
The same parameter is that the last one becomes Name ,null It means finding all the columns .
3、 Parameter metadata
Parameter metadata (ParameterMetaData): By PreparedStatement Object passing getParameterMetaData Method , Mainly aimed at PreparedStatement Object and its precompiled SQL Command statements provide some information ,ParameterMetaData The number of placeholder parameters that can be provided , Gets the placeholder for the specified location SQL Type, etc. .
3.1 Get precompiled SQL The number of placeholder parameters in the statement
@Test
void Test01() {
try {
String sql = "select * from t_user where uid = ?";
PreparedStatement pstmt = dataSourcee.getConnection().prepareStatement(sql);
// obtain ParameterMetaData object
ParameterMetaData paramMetaData = pstmt.getParameterMetaData();
pstmt.setString(1, "1");
// Get the number of parameters
int paramCount = paramMetaData.getParameterCount();
System.out.println(paramCount);
} catch (Exception throwables) {
throwables.printStackTrace();
}
}Of course, there are many other ways . This pair just learned JDBC Students who connect to the database should be familiar with , Anyway, I almost forgot .
4、 ResultSet Metadata
ResultSet Metadata (ResultSetMetaData): By ResultSet Object passing getMetaData Method , Mainly for the data Library executed SQL The result set object obtained by the script command ResultSet Some of the information provided in , For example, the number of columns in the result set 、 Specify the name of the column 、 Specifies the name of the column SQL Type, etc. , It can be said that this is a very important object for the framework .
Common methods are :
Method | explain |
getColumnCount | Get the number of column items in the result set |
getColumnType | Gets the SQL The type corresponds to Java in Types Class field |
getColumnTypeName | Gets the SQL type |
getClassName | Get the specified column SQL The type corresponds to Java The type of ( Package name plus class name ) |
@Test
void Test01() {
try {
String sql = "select * from t_user where uid = ?";
PreparedStatement pstmt = dataSourcee.getConnection().prepareStatement(sql);
// obtain ParameterMetaData object
ParameterMetaData paramMetaData = pstmt.getParameterMetaData();
pstmt.setString(1, "1");
// perform sql sentence
ResultSet rs = pstmt.executeQuery();
// obtain ResultSetMetaData object
ResultSetMetaData metaData = rs.getMetaData();
// Get the number of query fields
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
// Get column name
String columnName = metaData.getColumnName(i);
// obtain java type
String columnClassName = metaData.getColumnClassName(i);
// obtain sql type
String columnTypeName = metaData.getColumnTypeName(i);
System.out.println(" Column name "+columnName);
System.out.println("java type "+columnClassName);
System.out.println("sql type "+columnTypeName);
}
System.out.println(columnCount);
} catch (Exception throwables) {
throwables.printStackTrace();
}
}
边栏推荐
- R language plot visualization: visualize the normalized histograms of multiple data sets, add density curve KDE to the histograms, set different histograms to use different bin sizes, and add edge whi
- Brother sucks 590000 fans with his unique "quantum speed reading" skill: look at the street view for 0.1 seconds, and "snap" can be accurately found on the world map
- 10 common website security attack means and defense methods
- 【TcaplusDB知识库】Tmonitor单机安装指引介绍(一)
- File name setting causes an error to be written to writelines: oserror: [errno 22] invalid argument
- 导师邀请你继续跟他读博,你会不会立马答应?
- Eureka核心源码解析
- Advantages and disadvantages of distributed file storage system
- 多线程实现 重写run(),怎么注入使用mapper文件操作数据库
- Error im002 when Oracle connects to MySQL
猜你喜欢

【Methodot 专题】什么样的低代码平台更适合开发者?

直播電子商務應用程序開發需要什麼基本功能?未來發展前景如何?

Record in detail the implementation of yolact instance segmentation ncnn

C any() and aii() methods

记一次 .NET 某物管后台服务 卡死分析

Product strength benchmarking seal /model 3, with 179800 pre-sales of Chang'an dark blue sl03

Exception in Chinese character fuzzy query of MySQL database

导师邀请你继续跟他读博,你会不会立马答应?

What basic functions are required for live e-commerce application development? What is the future development prospect?

【TcaplusDB知识库】Tmonitor单机安装指引介绍(二)
随机推荐
直播电子商务应用程序开发需要什么基本功能?未来发展前景如何?
Array object in JS
3D mobile translate3d
go-zero微服务实战系列(七、请求量这么高该如何优化)
Audiotrack and audiolinker
多线程实现 重写run(),怎么注入使用mapper文件操作数据库
Memory compression for win10
oracle触发器 存储过程同时写入
[registration] infrastructure design: from architecture hot issues to industry changes | tf63
torchvision. models._ utils. Intermediatelayergetter tutorial
leetcode:522. Longest special sequence II [greed + subsequence judgment]
go-zero微服务实战系列(七、请求量这么高该如何优化)
数据库之元数据
Future & CompletionService
Oracle trigger stored procedure writes at the same time
【TcaplusDB知识库】TcaplusDB机器初始化和上架介绍
TCP/IP 详解(第 2 版) 笔记 / 3 链路层 / 3.4 桥接器与交换机 / 3.4.1 生成树协议(Spanning Tree Protocol (STP))
Multi thread implementation rewrites run (), how to inject and use mapper file to operate database
On June 23, the video address of station B in the third episode of rust chat room
Eureka核心源码解析