当前位置:网站首页>[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 :
边栏推荐
- 2022年在启牛开中银股票的账户安全吗?
- Deployment, recall and deletion solutions - stsadm and PowerShell "suggestions collection"
- Static test tool
- Datatable data conversion to entity
- cv2.resize函数报错:error: (-215:Assertion failed) func != 0 in function ‘cv::hal::resize‘
- Is it safe to open an account of BOC shares in kainiu in 2022?
- 2022 how to evaluate and select low code development platforms?
- 开户还得用身份证银行卡安全吗,我是小白不懂
- Is it safe to open an account online now? I want to know where I can open an account in Nanning now?
- ISO 26262 - considerations other than requirements based testing
猜你喜欢
Dry goods sharing | devaxpress v22.1 original help document download collection
Jerry's test box configuration channel [chapter]
QT compile IOT management platform 39 alarm linkage
Open source OA development platform: contract management user manual
MySQL storage expression error
ISO 26262 - considerations other than requirements based testing
嵌入式开发:如何为项目选择合适的RTOS?
Using enumeration to realize English to braille
South China x99 platform chicken blood tutorial
How does win11 time display the day of the week? How does win11 display the day of the week today?
随机推荐
I have to use my ID card to open an account. Is the bank card safe? I don't understand it
Demon daddy guide post - simple version
201215-03-19 - cocos2dx memory management - specific explanation "recommended collection"
How to integrate Google APIs with Google's application system (1) -introduction to Google APIs
Ten thousand word summary data storage, three knowledge points
Redis - basic use (key, string, list, set, Zset, hash, geo, bitmap, hyperloglog, transaction)
Actual combat: sqlserver 2008 Extended event XML is converted to standard table format [easy to understand]
Is it safe to open an account online now? I want to know where I can open an account in Nanning now?
Validutil, "Rethinking the setting of semi supervised learning on graphs"
Win11U盘不显示怎么办?Win11插U盘没反应的解决方法
An overview of the latest research progress of "efficient deep segmentation of labels" at Shanghai Jiaotong University, which comprehensively expounds the deep segmentation methods of unsupervised, ro
Is it safe to open an account of BOC shares in kainiu in 2022?
L2: current situation, prospects and pain points of ZK Rollup
648. Word replacement
EasyCVR配置中心录像计划页面调整分辨率时的显示优化
Use br to recover backup data on azure blob storage
智能交通焕发勃勃生机,未来会呈现哪些巨变?[通俗易懂]
Demon daddy A3 stage near normal speed speech flow initial contact
2022年在启牛开中银股票的账户安全吗?
MySQL storage expression error