当前位置:网站首页>[JDBC Part 1] overview, get connection, CRUD

[JDBC Part 1] overview, get connection, CRUD

2022-07-07 21:43:00 Sivan_ Xin


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

 Insert picture description here

Java And SQL Corresponding data type conversion table

 Insert picture description here

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 :
 Insert picture description here

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

  1. Get database connection .
  2. precompile sql sentence , return PreparedStatement.
  3. Fill in placeholders .
  4. perform execute() Method .
  5. close resource .

Use PreparedStatement Implement find operation

  1. Get database connection .
  2. precompile sql sentence , return PrepareStatement.
  3. Fill in placeholders .
  4. perform executeQuery() Method , And return the result set .
  5. Returns the metadata of the result set , To get the number of columns 、 Name .
  6. 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 column
    getColumnLabel(int column): Gets the alias of the specified column
    getColumnCount(): 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 :
     Insert picture description here
原网站

版权声明
本文为[Sivan_ Xin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071846314527.html

随机推荐