当前位置:网站首页>[JDBC Part 1] overview, get connection, CRUD
[JDBC Part 1] overview, get connection, CRUD
2022-07-07 21:43:00 【Sivan_ Xin】
List of articles
Code Uploaded : JDBC Code warehouse
01:JDBC summary
Note taking requires : You can write a program by reading the notes .
stay Java in , Database access technology can be divided into the following categories :
JDBC Direct access to database
JDO (Java Data Object ) technology
The third party O/R Tools , Such as Hibernate, Mybatis etc.
JDBC yes java The cornerstone of access to the database ,JDO、Hibernate、MyBatis It's just a better package JDBC.
JDBC Interface (API) There are two levels :
- Application oriented API:Java API, Abstract interface , For application developers ( Connect to database , perform SQL sentence , Get the results ).
- Database oriented API:Java Driver API, For developers to develop database drivers with .
JDBC yes sun The company provides a set of interfaces for database operation ,java Programmers only need to program for this set of interfaces .
Different database vendors , We need to focus on this set of interfaces , Provide different implementations . A collection of different implementations , It is the driver of different databases . ———— Interface oriented programming
JDBC Programming steps
Java And SQL Corresponding data type conversion table
02: Get database connection
In practice , The database needs 4 Basic information is loaded into the configuration file .
explain : Save configuration information in the form of a configuration file , Load the configuration file in the code . The benefits of using profiles :
① The separation of code and data is realized , If you need to modify the configuration information , Modify directly in the configuration file , There's no need to drill down into the code
② If the configuration information is modified , Save the process of recompiling .
Element 1 :Driver Interface implementation class
java.sql.Driver Interfaces are all JDBC The interface that the driver needs to implement . This interface is provided for database vendors , Different database vendors provide different implementations . There is no need to access the implementation directly in the program Driver The class of the interface , Instead, the driver manager class (java.sql.DriverManager) To call these Driver Realization .
- Load and register JDBC drive
MySQL The driver :com.mysql.cj.jdbc.Driver
.
The load driver :
Need to call Class Class static methods forName(), Pass it the... To be loaded JDBC The class name of the driver Class.forName(“com.mysql.cj.jdbc.Driver”);
Registration drive :
DriverManager Class is the driver manager class , Responsible for managing driver usage DriverManager.registerDriver(com.mysql.jdbc.Driver) To register the driver .
You don't usually call DriverManager Class registerDriver() Method to register an instance of a driver class , because Driver Interface driver classes contain static code blocks , In this static block of code , Would call DriverManager.registerDriver() Method to register an instance of itself .
The picture below is MySQL Of Driver Implementation class source code :
Element 2 :URL
JDBC URL Used to identify a registered driver , Driver manager through this URL Choose the right driver , So as to establish Database connection .
MySQL The connection of URL The way :jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc:mysql : agreement
localhost:ip Address
3306: Default mysql Port number
test:test database
Element three : User name and password
user,password It can be used “ Property name = Property value ” How to tell the database .
Last call DriverManager Class getConnection() Method to establish a connection to the database .
03: Use PreparedStatement Realization CRUD operation
C:create、R:Retrieve、U:Update、D:Delete.
PrepareStatement Introduction to
- You can call Connection Object's preparedStatement(String sql) Method to get PreparedStatement object
- PreparedStatement Interface is Statement Sub interface of , It represents a precompiled SQL sentence .
- PreparedStatement The object represents SQL The parameters in the statement are marked with question marks (?) To express , call PreparedStatement Object's setXxx() Method to set these parameters ..
- setXxx() Method has two parameters , The first parameter is to be set SQL The index of the parameter in the statement ( from 1 Start ), The second one is set up SQL The value of the parameter in the statement .
PreparedStatement vs Statement
Readability and maintainability of code .
PreparedStatement To maximize performance :
DBServer Provides performance optimization for precompiled statements . Because precompiled statements can be called repeatedly , So the sentence is being DBServer The compiled execution code of the compiler is cached , So the next time you call it, you don't need to compile as long as it's the same precompiled statement , As long as the parameters are directly passed into the compiled statement execution code, it will be executed .stay statement In the sentence , Even though the data is different, the operation is different , So the whole statement itself doesn't match , There is no sense of caching statements . The fact is that no database caches the compiled execution code of ordinary statements . In this way, the incoming statement is compiled every time it is executed .
( Syntax check , Semantic check , Translated into binary commands , cache )
PreparedStatement Can prevent SQL Inject
Use PreparedStatement Steps for adding, deleting and modifying
- Get database connection .
- precompile sql sentence , return PreparedStatement.
- Fill in placeholders .
- perform execute() Method .
- close resource .
Use PreparedStatement Implement find operation
- Get database connection .
- precompile sql sentence , return PrepareStatement.
- Fill in placeholders .
- perform executeQuery() Method , And return the result set .
- Returns the metadata of the result set , To get the number of columns 、 Name .
- Using reflection , For dynamic objects columnName Property is assigned to columnValue. In order to return query results .( The first 6 Here we use ORM thought )
Need to use ResultSet And ResultSetMetaData:
Result:
- The query needs to call PreparedStatement Of executeQuery() Method , The query result is a ResultSet object
- ResultSet Object encapsulates the result set of database operations in the form of logical tables ,ResultSet The interface is provided and implemented by the database manufacturer ResultSet What is returned is actually a data table . There is a pointer to the front of the first record in the data table .
- ResultSet Object maintains a cursor to the current row of data , In the beginning , The cursor is before the first line , Can pass ResultSet object Of next() Method moves to the next line . call next() Method to check whether the next line is valid . If it works , This method returns true, And the pointer moves down . amount to Iterator Object's hasNext() and next() A combination of methods .
- When the pointer points to a line , You can call getXxx(int index) or getXxx(int columnName) Get the value of each column .
for example : getInt(1), getString(“name”)
Be careful :Java Interaction with the database is related to Java API All the indexes in are from 1 Start .
ResultSetMetaData:
- Can be used to get information about ResultSet In the object Column type and attribute information The object of
ResultSetMetaData meta = rs.getMetaData()
;getColumnName(int column)
: Gets the name of the specified columngetColumnLabel(int column)
: Gets the alias of the specified columngetColumnCount()
: Returns the current ResultSet Number of columns in object .
getColumnTypeName(int column): Retrieve the database specific type name of the specified column . getColumnDisplaySize(int column): Indicates the maximum standard width of the specified column , In characters . isNullable(int column): Indicates whether the value in the specified column can be null.
isAutoIncrement(int column): Indicates whether the specified column is automatically numbered , So the columns are still read-only .
Summary
- Two thoughts
The idea of interface oriented programming
ORM 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
- Two kinds of technology
JDBC Metadata for the result set :ResultSetMetaData
Get the number of columns :getColumnCount()
Get the alias of the column :getColumnLabel()
By reflection , Create an object of the specified class , Gets the specified property and assigns a value to it
- Find the flow diagram of the operation :
边栏推荐
- 特征生成
- Reptile combat (VII): pictures of the king of reptiles' heroes
- Do you have to make money in the account to open an account? Is the fund safe?
- UVA 11080 – Place the Guards(二分图判定)
- Use camunda to do workflow design and reject operations
- How does win11 unblock the keyboard? Method of unlocking keyboard in win11
- MinGW MinGW-w64 TDM-GCC等工具链之间的差别与联系「建议收藏」
- Contour layout of margin
- Unity3d 4.3.4f1执行项目
- 嵌入式开发:如何为项目选择合适的RTOS?
猜你喜欢
Redis - basic use (key, string, list, set, Zset, hash, geo, bitmap, hyperloglog, transaction)
你可曾迷茫?曾经的测试/开发程序员,懵懂的小菜C鸟升级......
Google SEO external chain backlinks research tool recommendation
L2:ZK-Rollup的现状,前景和痛点
Jerry's initiation of ear pairing, reconnection, and opening of discoverable and connectable cyclic functions [chapter]
[开源] .Net ORM 访问 Firebird 数据库
Jerry's test box configuration channel [chapter]
L2: current situation, prospects and pain points of ZK Rollup
How does win11 time display the day of the week? How does win11 display the day of the week today?
Open source OA development platform: contract management user manual
随机推荐
How can big state-owned banks break the anti fraud dilemma?
[UVALive 6663 Count the Regions] (dfs + 离散化)[通俗易懂]
Demon daddy guide post - simple version
Intelligent transportation is full of vitality. What will happen in the future? [easy to understand]
Can I open a stock account directly online now? Is it safe?
Hdu4876zcc love cards (multi check questions)
Lingyun going to sea | saihe & Huawei cloud: jointly help the sustainable development of cross-border e-commerce industry
201215-03-19 - cocos2dx memory management - specific explanation "recommended collection"
Addition, deletion, modification and query of sqlhelper
Code of "digital image processing principle and Practice (matlab version)" part2[easy to understand]
UVA 12230 – crossing rivers (probability) "suggested collection"
Codeforces Round #296 (Div. 2) A. Playing with Paper[通俗易懂]
How to turn on win11 game mode? How to turn on game mode in win11
Reinforcement learning - learning notes 8 | Q-learning
Unity3d 4.3.4f1 execution project
Using enumeration to realize English to braille
Index summary (assault version)
Description of the difference between character varying and character in PostgreSQL database
Jerry's power on automatic pairing [chapter]
How polardb-x does distributed database hotspot analysis