Jdbc notes-basic concepts

The basic steps of using JDBC

  1. Import the driver jar package
  2. Load the driver class file
  3. Get database link object
  4. Define sql statement
  5. Set parameters, execute sql
  6. Get results
  7. Release resources

A typical code example is as follows:

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root");
String sql = "select * from accout where id = 1";
Statement stmt = conn.createStatement(sql);
ResultSet result = stmt.execute(sql);
stmt.close();
conn.close():

JDBC objects

  1. DriverManager: drive management object

    Features

    1. Register driver

      public static synchronized void registerDriver(java.sql.Driver driver)
      

      But when writing code, the registered driver uses

      Class.forName("com.mysql.jdbc.Driver");
      

      After entering com.mysql.jdbc.Driver, I found that registerDrvier in DriverManager was called in the static code block

      static {
              
              
              try {
              
              
                  DriverManager.registerDriver(new Driver());
              } catch (SQLException var1) {
              
              
                  throw new RuntimeException("Can't register driver!");
              }
          }
      

      In fact, when using the driver jar package after mysql 5, you can omit the step of registering the driver . This is because in the mysql driver jar package, the driver interface implementation class is configured through META-INF/services, so that through the Java SPI The mechanism will automatically load the com.mysql.jdbc.Driver class.

    2. Get database connection

      public static Connection getConnection(String url,String username,String password);
      

      The syntax format of url:

      jdbc:mysql://ip地址(域名):端口/数据库名称

      such asjdbc:mysql://localhost:3306/user

      If you call local mysql and the port is 3306, the url can be abbreviated as

      jdbc:mysql:///user

  2. Connection: database connection object

    Features

    1. Get the object that executes sql (Statement)

      Statement createStatement();
      PreparedStatement prepareStatement(String sql)
      
    2. Management affairs

      1. Open transaction

        Passing in false means that you want to manually commit the transaction, and you will not submit a transaction by default to execute a row of Sql, so that you can control multiple Sql in a transaction

        void setAutoCommit(boolean autoCommit);

      2. Commit transaction

        void commit()

      3. Rollback transaction

        void rollback()

  3. Statement: Object to execute SQL

    Static SQL, there is a risk of SQL injection

    Execute SQL

    1. boolean execute(String sql)

      Any sql can be executed. If it returns true, it means that the result of the execution is a ResultSet object; if it returns false, it means that it is an operation such as an update count, or there is no ResultSet returned.

    2. int executeUpdate(String sql)

      Generally used to execute DML statements (insert/delete/update), can also execute DDL (create/alter/drop)

      The return value is the number of rows affected by the sql . If there are a total of 5 records in the user table, the address value is "Sichuan", and the name value of 1 of the 5 records is yogurt, and the name of the other 4 records If neither is yogurt, execute sql

      UPDATE user SET name = "yogurt" WHERE address="四川"
      

      The number of affected rows is 4 rows

    3. Result executeQuery(String sql)

      Execute DQL (select) statement

  4. ResultSet: The result set object, which encapsulates the query result

    When the Statement is just executed, the cursor of the ResultSet obtained points to the position before the first row of records. You need to call the next() method before reading the data. Generally, we will read the data in the ResultSet like this (somewhat like Usage of Iterator)

    ResultSet result = stmt.executeQuery(sql);
    while(result.next()){
          
          
        //读取数据
    }
    
    1. boolean next() The cursor moves down one row. If the row currently pointed to has data, it returns true. If there is no data, if it returns false, it means that the data has been read and the cursor has reached the position after the last row.

    2. getXxx(参数) Get data, specifically get a column of the current row

      The parameter can be int columnIndex, representing the column number, starting from 1

      The parameter can also be String columnLabel, representing the column name

      Xxx represents the type, such as getInt(1), getString(1)

  5. PreparedStatement

    It will be pre-compiled and then dynamically assembled parameters to prevent SQL injection.

    Parameter use? as a placeholder

    PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM product WHERE name = ?");
    pstmt.setString(1,"无尽之刃"); //注意占位符?的下标从1开始
    ResultSet result = pstmt.executeQuery();
    

Guess you like

Origin blog.csdn.net/vcj1009784814/article/details/106131646