1

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
  • maybe this will help you stackoverflow.com/questions/7886462/… they have a few answers about count rows Commented Aug 31, 2022 at 10:27
  • Do you mean that you want to count the number of columns in a particular database table? Are you familiar with interface DatabaseMetaData? Call method getColumns, iterate through the ResultSet and count the number of rows. Commented Aug 31, 2022 at 16:57

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.