JDBC novice summary

1.JDBC

Insert picture description here

  • Function: The function is to operate the database through JAVA, which is essentially a set of specifications (interface)
  • Decoupling: JDBC specification (interface) (DB2, sqlserver, Oracle, mysql, maridb)

JDBC writing steps

  1. Guide package
  2. Register driver
  3. establish connection
  4. Get statement execution object
  5. Get ResultSet
  6. Analysis result
  7. Close resource

2. Protocol: what will trigger class loading

  1. new
  2. Use static methods
  3. The parent class is loaded when the subclass is loaded

The role of class loader

Load the class file we wrote into the jvm memory (permanent generation)

3. Connetion (connection)

  1. Create Statement object
  2. Administrative Affairs (ACID)
  3. Atomicity A
  4. Consistency C
  5. Isolation I
  6. Persistence D
  7. Create user table, add user information

Sql injection attack

  • Function: Use a special sql format to log in with incorrect passwords, and finally query data correctly
  1. The concept of JDBC, JAVA operation relational database specification

  2. Mainly contains API

    1. DriverManager
    2. Connection
    3. Statement
    4. ResultSet
  3. Add, delete, modify

    1. Check: consistent with hello
    2. 改: executeUpdate() : int
    3. 增:executeUpdate() : int
    4. 删: executeUpdate() : int
  4. JDBC tools

    1. Is to simplify our code for getting links and closing resources
    2. Implementation steps:
      1. Configuration file
      2. Load configuration file
      3. Get link method
      4. Release resource method
  5. Integrate code into web project

  6. sql injection

    1. The implementation method is to splice strings to realize that SQL can query data normally in the case of a wrong password.
SELECT * FROM user WHERE loginname= '' or 1 = 1 -- AND password='" + password + "'

prepareStatement

  • Role: Pre-compiled SQL statements to prevent SQL injection problems

  • use:

    • create:

      PrepareStatement ps = connection.prepareStatement("select * from student where id = ?");
      ps.setInt(1, 22);   
      
    • carried out

      • Query: ps.executeQuery()
      • Modification: ps.executeUpdate()

Transaction management

  • Use object: Connection object

  • Transaction method:

    • Open transaction: setAutoCommit(false)
    • How to submit: commit()
    • Rollback: rollback()
  • Account, transfer case list

    C3P0 connection pool

    step

    1. Guide package (and mysql driver package,)

    2. Configuration information c3p0-config.xml -> information to connect to the database

    parameter:

    initialPoolSize  //初始连接数量
    maxPoolSize  //最大连接数量
    checkTimeOut //等待时间
     // 3.直接创建
    new combopooledDataSource();
    
    

c3p0 test

Create CombopooledDataSource directly

public class C3P0Test1 {
    
    
    public static void main(String[] args) throws Exception{
    
    
        //1.创建c3p0的数据库连接池对象
        DataSource dataSource = new ComboPooledDataSource();

        //2.通过连接池对象获取数据库连接
        Connection con = dataSource.getConnection();


        //3.执行操作
        String sql = "SELECT * FROM student";
        PreparedStatement pst = con.prepareStatement(sql);

        //4.执行sql语句,接收结果集
        ResultSet rs = pst.executeQuery();

        //5.处理结果集
        while(rs.next()) {
    
    
            System.out.println(rs.getInt("sid") + "\t" + rs.getString("name") + "\t" + rs.getInt("age") + "\t" + rs.getDate("birthday"));
        }

        //6.释放资源
        rs.close();
        pst.close();
        con.close();
    }
}

druid

step

1. Guide package

2. Configuration file: druid.properties

initialSize

maxActive

maxWait

3. Load the configuration file-classloader () through the properties collection

  1. Get the stream object of the configuration file

  2. Put the stream object in load()

  3. Through the connection factory class

    Code

        public static void main(String[] args) throws Exception {
          
          
            InputStream inputStream = Demo2_Druid.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            Connection connection = dataSource.getConnection();
            String sql = "select * from student";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
          
          
                System.out.println(resultSet.getInt("sid") + "\t" + resultSet.getString("name") + "\t" + resultSet.getInt("age") + "\t" + resultSet.getDate("birthday"));
            }
           
            statement.close();
            resultSet.close();
            connection.close();
    
        }
    

Expansion: Strategic Model

Code:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directlyInsert picture description here

  • Executor
  • Strategy (interface)
  • Caller (calling strategy passed to executor) implementation class

BeanHandler implementation class -> role: convert the result set into an object

DataBaseMetaData database source information

//获取数据库产品名字
String getDatabaseProductName();
//获取数据库产品版本
int getDatabaseProductVersion();
//1.User--->Musql
preparedStatement.getMetaData()
//2.Mysql--->User
resultSet.getMetaData()

Basic overview of metadata

What are meta annotations?

Annotation is called meta-annotation.

What is metadata?
Insert picture description here

Parameter metadata: ParameterMetaData

aims

API and cases for parameter metadata

Get ParameterMetaData

Methods in the PreparedStatement interface Description
ParameterMetaData getParameterMetaData() Obtain parameter metadata through prepared statements

Methods in the interface

Because it is an interface, it needs the support of the database manufacturer's driver. MySQL's support for parameter metadata is not ideal, but it does not affect today's use

Methods in the ParameterMetaData interface Description
int getParameterCount() Get the number of parameters
String getParameterTypeName(int param) Get the data type of a column parameter, the parameter is the column number, starting from 1
can only get varchar type data

Parameter metadata: ParameterMetaData

aims

API and cases for parameter metadata

Get ParameterMetaData

Methods in the PreparedStatement interface Description
ParameterMetaData getParameterMetaData() Obtain parameter metadata through prepared statements

Methods in the interface

Because it is an interface, it needs the support of the database manufacturer's driver. MySQL's support for parameter metadata is not ideal, but it does not affect today's use

Methods in the ParameterMetaData interface Description
int getParameterCount() Get the number of parameters
String getParameterTypeName(int param) Get the data type of a column parameter, the parameter is the column number, starting from 1
can only get varchar type data

Guess you like

Origin blog.csdn.net/weixin_47785112/article/details/106766353