当前位置:网站首页>[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 :
边栏推荐
- SQL injection error report injection function graphic explanation
- 201215-03-19 - cocos2dx memory management - specific explanation "recommended collection"
- Intelligent transportation is full of vitality. What will happen in the future? [easy to understand]
- Virtual machine network configuration in VMWare
- Devil daddy A0 English zero foundation self-improvement Road
- ISO 26262 - considerations other than requirements based testing
- Cocos2d-x 游戏存档[通俗易懂]
- NVR硬盤錄像機通過國標GB28181協議接入EasyCVR,設備通道信息不顯示是什麼原因?
- Arlo's troubles
- 私募基金在中國合法嗎?安全嗎?
猜你喜欢
Have you ever been confused? Once a test / development programmer, ignorant gadget C bird upgrade
Dry goods sharing | devaxpress v22.1 original help document download collection
Win11如何解禁键盘?Win11解禁键盘的方法
L'enregistreur de disque dur NVR est connecté à easycvr par le Protocole GB 28181. Quelle est la raison pour laquelle l'information sur le canal de l'appareil n'est pas affichée?
Solve the problem of using uni app mediaerror mediaerror errorcode -5
Talk about relational database and serverless
Goal: do not exclude yaml syntax. Try to get started quickly
Jerry's about TWS channel configuration [chapter]
Solve the problem of uni in uni app Request sent a post request without response.
Ad domain group policy management
随机推荐
Can Huatai Securities achieve Commission in case of any accident? Is it safe to open an account
Demon daddy A1 speech listening initial challenge
DataTable数据转换为实体
FatMouse' Trade(杭电1009)
cv2.resize函数报错:error: (-215:Assertion failed) func != 0 in function ‘cv::hal::resize‘
Validutil, "Rethinking the setting of semi supervised learning on graphs"
Navicat connect 2002 - can't connect to local MySQL server through socket '/var/lib/mysql/mysql Sock 'solve
Hdu4876zcc love cards (multi check questions)
Codeforces Round #296 (Div. 2) A. Playing with Paper[通俗易懂]
The new version of onespin 360 DV has been released, refreshing the experience of FPGA formal verification function
Debugging and handling the problem of jamming for about 30s during SSH login
NVR硬盘录像机通过国标GB28181协议接入EasyCVR,设备通道信息不显示是什么原因?
2022年在启牛开中银股票的账户安全吗?
Qt编写物联网管理平台39-报警联动
Feature generation
Codeforces Round #275 (Div. 2) C – Diverse Permutation (构造)[通俗易懂]
Use br to back up tidb cluster data to azure blob storage
Arlo's troubles
Addition, deletion, modification and query of sqlhelper
开户必须往账户里面赚钱吗,资金安全吗?