当前位置:网站首页>[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 :
边栏推荐
- How much does it cost to develop a small program mall?
- 死锁的产生条件和预防处理[通俗易懂]
- 2022 how to evaluate and select low code development platforms?
- What stocks can a new account holder buy? Is the stock trading account safe
- Use br to recover backup data on azure blob storage
- Code of "digital image processing principle and Practice (matlab version)" part2[easy to understand]
- Wechat official account oauth2.0 authorizes login and displays user information
- HDU4876ZCC loves cards(多校题)
- Implementation of mahout Pearson correlation
- 解决uni-app中uni.request发送POST请求没有反应。
猜你喜欢
Using enumeration to realize English to braille
为什么Win11不能显示秒数?Win11时间不显示秒怎么解决?
SQL injection error report injection function graphic explanation
【JDBC Part 1】概述、获取连接、CRUD
解决uni-app中uni.request发送POST请求没有反应。
Jerry's manual matching method [chapter]
Win11U盘不显示怎么办?Win11插U盘没反应的解决方法
[C language] advanced pointer --- do you really understand pointer?
Demon daddy B3 read extensively in a small amount, and completed 20000 vocabulary+
Dry goods sharing | devaxpress v22.1 original help document download collection
随机推荐
Ad domain group policy management
华泰证券可以做到万一佣金吗,万一开户安全嘛
Devil daddy B1 hearing the last barrier, break through with all his strength
Description of the difference between character varying and character in PostgreSQL database
Can Huatai Securities achieve Commission in case of any accident? Is it safe to open an account
Awk processing JSON processing
Demon daddy B3 read extensively in a small amount, and completed 20000 vocabulary+
Codemail auto collation code of visual studio plug-in
L2: current situation, prospects and pain points of ZK Rollup
Win11如何解禁键盘?Win11解禁键盘的方法
私募基金在中国合法吗?安全吗?
Unity3d 4.3.4f1 execution project
ISO 26262 - considerations other than requirements based testing
Solve the problem of using uni app mediaerror mediaerror errorcode -5
Song list 11111
Differences and connections between MinGW, mingw-w64, tdm-gcc and other tool chains "suggestions collection"
MySQL storage expression error
L2:ZK-Rollup的现状,前景和痛点
Jerry's power on automatic pairing [chapter]
Is private equity legal in China? Is it safe?