How to count fields in access table with Java?

Viewed 39

i am working on a project to edit access tables without access ,but with java so i want to get the count of fields of the table


This is the code :

package DatabaseEditor;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DatabaseOptions {

    Connection con;
    String url = "jdbc:ucanaccess://databases\\Saves.mdb";
    
    public int getFields() {
        int data = "";


        try {
            con = DriverManager.getConnection(url);

            String sql = "SELECT * FROM Workers";
            
            PreparedStatement stat = con.prepareStatement(sql);
            
            stat.executeQuery(sql);
            ResultSet rs = stat.getResultSet();
            
            //Here i want to set data value to count of fields
                            
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

}

getFields() function i'll run it in the start of another script

2 Answers

sql = "show full columns from table_name" and the rs.getFetchSize() is fields count

As Abra already suggested in the comments, you could use the DatabaseMetaData interface for fetching such information. Below is a minimal code example, credits for research and theory go to Abra.

package DatabaseEditor;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DatabaseOptions {

    Connection con;
    String url = "jdbc:ucanaccess://databases\\Saves.mdb";
    
    public int getFields() {
        try {
            con = DriverManager.getConnection(url);
            DatabaseMetaData metaData = con.getMetaData();
            
            int numberOfFields = 0;
            ResultSet columns = metaData.getColumns(null, null, "Workers", null);
            
            while (columns.next()) {
                ++numberOfFields;
            }

            return numberOfFields;
        } finally {
            con.close();
        }
    }
}
Related