Over a million developers have joined DZone.

Execute Arbitary SQL In JDBC & Get Column Names Etc From The Meta Data

·
This will execute an arbitary SQL string in JDBC and extract the column names. I extracted this code from a much larger module I wrote years ago, so it isn't complete and hasn't been tested. You have been warned.


    /*
    ** connection is a java.sql.Connection obtained in the usual way.
    */

    PreparedStatement statement =
	connection.prepareStatement (sqlString);
    statement.setMaxRows (configModel.getMaxRows ());

    if (statement.execute ())
    {
	ResultSet resultSet = statement.getResultSet ();
	ResultSetMetaData metaData = resultSet.getMetaData ();

	/*
	** Get the column names.
	*/

	for (int i = 0 ; i < metaData.getColumnCount () ; i++)
	{
	    int columnType = metaData.getColumnType (i + 1);
	    String columnName = metaData.getColumnLabel (i + 1);

	    /*
	    ** Do something with columnType & columnName.
	    */

	}

	/*
	** Fetch the rows.
	*/

	while (resultSet.next ())
	{
	    String value;

	    for (int i = 0 ; i < metaData.getColumnCount () ; i++)
		value = resultSet.getString (i + 1);
	}
    }
    else
    {
	/*
	** Query was probably update/insert/delete.
	*/

	int rowCount = statement.getUpdateCount ();
    }

    statement.close ();
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}