JDBC的执行流程

354 阅读1分钟

1.注册驱动

2.根据URL创建数据库连接

3.获得数据库的Statement对象并传入sql语句编译

4.发送sql语句并获得返回结果

5.解析返回结果

6.关闭数据库连接

import entity.User;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class TestJDBCConnection {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");  //注册驱动
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<User> users = new ArrayList<>();
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_test_temp?user=root&password=BXS552ZXY");    //建立数据库连接
            preparedStatement =
                    connection.prepareStatement("select id,username,password from user");
            resultSet = preparedStatement.executeQuery();   //执行sql并带回返回结果
            ResultSetMetaData metaData = resultSet.getMetaData();
            int fieldCount = metaData.getColumnCount();
            Class<User> clazz = (Class<User>) Class.forName("entity.User");
            //遍历结果集解析查询结果
            while (resultSet.next()) {
                User user = clazz.newInstance();
                for (int i = 1; i <= fieldCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Field declaredField = clazz.getDeclaredField(columnName);
                    declaredField.setAccessible(true);
                    declaredField.set(user, resultSet.getObject(i)); //如果一切正常,设置的数据类型会被强转为实体类中对应的成员的属性的数据类型
                }
                users.add(user);
            }

            users.forEach(System.out::println);
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭数据库连接
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}