JAVA technology sharing: jdbc analysis

# jdbc analysis

# 1. The concept

of jdbc The so-called jdbc is actually an abbreviation from java database conectivity. As the name suggests, it is used to connect the database in the java program, so that the database can be operated. In fact, jdbc is a specification for java programs to communicate with databases. This specification (interface) is defined under the java.sql package. Its four core objects:

- DriverManager: used to load database drivers
- Connection: used to connect to the database
- Statement: used to execute sql statements
- ResultSet: used to encapsulate the result set returned from the database

# Second, jdbc first experience

```java
        //1. Register the driver
        Class.forName("com.mysql.jdbc.Driver");
        //2. Get a connection object
        String url= "jdbc:mysql:///db_day07?user=root&password= 123";
        Connection connection = DriverManager.getConnection(url);
        //3. Get the statement object that executes the sql statement
        Statement stmt = connection.createStatement();
        //4. Execute the sql statement
        String sql = "select * from user";
        //5. Get the result set object ResultSet, which encapsulates all the data from the database
        ResultSet rs = stmt.executeQuery(sql);
        //6. Parse the result set
        while(rs. next()){
            System.out.println(rs.getInt(1)+";"+rs.getString(2)+";"+rs.getInt(3)+";"+rs.getString(4) );
        }
        //7. Release resources rs.close(
        );
        stmt.close();
        connection.close();
```

## The role of the database driver: The

database driver is a class set that has implemented the jdbc specification. It encapsulates all the classes that implement the jdbc specification.

For the mysql driver, the obtained Connection object can connect to the mysql database. Similarly, the connection object obtained by the oracle driver can connect to the oracle database.

# 3. Detailed explanation of the four core objects

## 1. DriverManager: Loading drivers

There are two ways to register drivers:

1) DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 

This method is not suitable, because the driver will be registered with the loading of the com.mysql.jdbc.Driver class, which is equivalent to registering two 2

) Class.forName("com.mysql.jdbc.Driver"); In this way, the com.mysql.jdbc.Driver class is loaded directly, and the static code block of the Driver class will register the driver when the class is loaded. Therefore, register the driver in this way

## 2.Connection:

What kind of database driver is connected to the database, the obtained connection object is what kind of database to connect to, such as the mysql database driver, the obtained connection object is used for connection mysql database.

Ways to get Connection object:

- Way 1:

```java
        String url = "jdbc:mysql://localhost:3306/db_day07";
        String user = "root";
        String password = "123";
        Connection conn = DriverManager. getConnection(url, user, password);






        pro.setProperty("user", "root");
        pro.setProperty("password", "123");
        Connection conn = DriverManager.getConnection(url, pro);
```

- Method 3: use username and password as Parameters of url

```java
        String url= "jdbc:mysql:///db_day07?user=root&password=123";
        Connection conn = DriverManager.getConnection(url);
```

## 3.Statement object: used to execute

The method of obtaining the object of the sql statement :

createStatement() of the Connection object;

the method of executing the sql statement:

- Method 1: executeQuery(String sql): The return value is a ResultSet object, which encapsulates the result of the query.

  For the sql statement of the query, use this method. Because the sql (select) of the query will produce a result set.

- Method 2: executeUpdate(String sql): The return value is an int representing the number of rows affected.

  For SQL statements (insert, update, delete) that do not produce results, use this method, and the return value of this method is the number of rows affected.

## 4.ResultSet object: used to encapsulate the result set

  If the statement object executes the executeQuery method and produces a result, then the result set is encapsulated into the ResultSet object.

  Several methods need to be mastered:

- next(): Before the first call, the cursor points to the first line, the first call refers to the first line, and the second call refers to the second line. The return value of the next method, if the row has data, returns true, otherwise returns false.
- getInt(int columnindex): find the data of the column through the index of the column, note that the index starts from 1
    - getInt(String columnname): Find the data for that column by its name.
    - getString(), getObject()...

# Fourth, improve the JDBC code

## Encapsulate the JDBCUtil tool class, and obtain the Connection object through the tool class

```java
private static String driver = null;
    private static String url = null;
    private static String user = null;
    private static String password = null;
    static{
        //The static code block is loaded as the class is loaded, and only once.
        Properties p = new Properties();
        try {
            p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("dbinfo.properties"));
            driver = p.getProperty("driver");
            url = p.getProperty("url");
            user = p.getProperty("user");
            password = p.getProperty("password");
            Class.forName(driver);
        
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    public static Connection getConnection() throws SQLException, ClassNotFoundException{
        return DriverManager.getConnection(url,user,password);
    }
```

# 5. Case: complete login verification

Implementation of login verification

```java
public User findUser(String username, String password) {
        User user = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //Get a Connection object from the tool class
            conn = JDBCUtil.getConnection();
            stmt = conn.createStatement( );
            //select * from user where username='zhangsan' and password='123456'
            String sql = "select * from user where username='"+username
                    +"' and password='"+password+"'";
            rs = stmt.executeQuery(sql);
            
            if(rs.next()){
                //if If the username and password are correct, then you can get a record, so parse the record and encapsulate it in the User object
                user = new User();
                user.setUid(rs.getString(1));
                user.setUsername(rs.getString(2) ));
                user.setPassword(rs.getString(3));
            }
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            //Release resources
            JDBCUtil.releaseResource(conn, stmt, rs);
        }
        return user;
    }
    
```

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609843&siteId=291194637