Home  >  Article  >  Java  >  How does Java code read a database table?

How does Java code read a database table?

WBOY
WBOYforward
2023-05-08 09:55:071283browse

Java reads database table

package com.easycrud.builder;
import com.easycrud.utils.PropertiesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
/**
 * @BelongsProject: EasyCrud
 * @BelongsPackage: com.easycrud.builder
 * @Author: xpx
 * @Email: 2436846019@qq.com
 * @CreateTime: 2023-05-02  18:02
 * @Description: 读Table
 * @Version: 1.0
 */
public class BuildTable {
    private static final Logger logger = LoggerFactory.getLogger(BuildTable.class);
    private static Connection conn = null;
    /**
     * 查表名和表注释
     */
    private static String SQL_SHOW_TABLE_STATUS = "show table status";
    /**
     * 读配置,连接数据库
     */
    static {
        String driverName = PropertiesUtils.getString("db.driver.name");
        String url = PropertiesUtils.getString("db.url");
        String user = PropertiesUtils.getString("db.username");
        String password = PropertiesUtils.getString("db.password");
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url,user,password);
        } catch (Exception e) {
            logger.error("数据库连接失败",e);
        }
    }
    /**
     * 读取表
     */
    public static void getTables() {
        PreparedStatement ps = null;
        ResultSet tableResult = null;
        try{
            ps = conn.prepareStatement(SQL_SHOW_TABLE_STATUS);
            tableResult = ps.executeQuery();
            while(tableResult.next()) {
                String tableName = tableResult.getString("name");
                String comment = tableResult.getString("comment");
                logger.info("tableName:{},comment:{}",tableName,comment);
            }
        }catch (Exception e){
            logger.error("读取表失败",e);
        }finally {
            if (tableResult != null) {
                try {
                    tableResult.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Novice guide

Logger

The log that comes with Java.

Common usage is as follows, print log information:

logger.error("Database connection failed",e)

logger.info("tableName:{},comment: {}", tableName, comment), {} is the placeholder

LoggerFactory.getLogger(xxx.class)

Specify the class to initialize the log object. When outputting the log, you can print it out The category of the log information.

Connection

The Connection object is used to open a connection to a data source.

Class.forName(driverName)

Load the driver.

DriverManager.getConnection(url,user,password)

Get the database connection.

PreparedStatement

One of the APIs used to execute SQL query statements.

ResultSet

The result set (ResultSet) is an object returned by the query results in the data. The result set is an object that stores the query results.

ps = conn.prepareStatement(SQL_SHOW_TABLE_STATUS)

The SQL statement will be precompiled before execution, and then the SQL statement will be executed and the result will be returned.

tableResult = ps.executeQuery()

Store the query results of the database response in the ResultSet class object for our use.

next() method in ResultSet

The initial position of the pointer in ResultSet is before the first line; calling the next() method for the first time will set the first line to the current line.

name and comment

respectively represent the table name and table comment queried after executing the database show table status statement. Use the getString() method of ResultSet to get the corresponding value.

The above is the detailed content of How does Java code read a database table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete