Reputation: 2353
I'm working on a program that makes using MySQL databases simpler. Right now I have to create forms to add and edit data from the tables within the database. The problem is that when I create the form I don't want to display fields for auto-incremented columns. All I need is the name of the column to fix this but I have no idea how to find the name of a auto-incremented column. I have tried looking up the answer but all I find is information about finding auto - generated keys. Can someone help me or point me in the right direction? Thanks for the help.
UPDATE: Thanks for the help. Base on the answers below I came up with this method:
public Vector<String> getAutoIncrementedColumns(String table) {
Vector<String> columnNames = new Vector<String>();
Connection connection;
try {
connection = DriverManager.getConnection(getUrl(), getUser(),
getPassword());
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("Select * from "+table);
int columnCount = result.getMetaData().getColumnCount();
for(int i = 1; i <=columnCount; i++){
if(result.getMetaData().isAutoIncrement(i)){
columnNames.add(result.getMetaData().getColumnName(i));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return columnNames;
}
Upvotes: 3
Views: 1872
Reputation: 2773
If you have access to the schema information_schema
these informations are available from the tables
Upvotes: 0
Reputation: 6153
The class ResultSetMetaData can provide this information.
But you would have to execute a select *
first to get a result set. You could do
SELECT * FROM table LIMIT 1
to get the result set.
Upvotes: 0
Reputation: 8839
Once you have a ResultSet
, you can call its getMetaData
method to the get a ResultSetMetaData object. From there, you can use the isAutoIncrement
method to determine if a column is an AUTO_INCREMENT column, and getColumnName
to get the column's name.
Upvotes: 4
Reputation: 18334
The EXTRA
column of the INFORMATION_SCHEMA.COLUMNS
table should have this information.
PS:this is from top of my head. Don't have MySql handy, you may have to test to confirm.
Upvotes: 1