E.g.: fname is a string, salary is a double, and so on.
|
ResultSet rset; rset = SQLstatement.executeQuery("SQL-query"); |
We can use the ResultSet object to obtain the meta data on the result set
(The structure of the result set is stored inside the ResultSet object)
(1) Execute a query: ResultSet rset; rset = SQLstatement.executeQuery("SQL-query"); |
The meta data of the result set is stored in the ResultSetMetaData typed variable metaData
|
ResultSet rset; rset = SQLstatement.executeQuery("SQL-query"); ResultSetMetaData metaData; // Define variable to hold meta data metaData = rset.getMetaData(); // Get meta data of result set |
import java.sql.*; public class MetaData { String url = "jdbc:mysql://holland.mathcs.emory.edu:3306/"; String dbName = "companyDB"; String userName = "cs377"; String password = "abc123"; public static void main (String args[]) { try { // Load the MySQL JDBC driver DriverManager.registerDriver( new com.mysql.jdbc.Driver() ); } catch (Exception e) { System.out.println("Failed to load JDBC driver."); return; } Connection conn = null; Statement stmt = null; try { // Connect to the database conn = DriverManager.getConnection(url+dbName,userName,password); // Allocate buffer to execute SQL statements stmt = conn.createStatement (); } catch (Exception e) { System.err.println("problems connecting to " + url+dbName); } try { // Execute an SQL command ResultSet rset = stmt.executeQuery("select * from employee"); // Get the meta data ResultSetMetaData meta = rset.getMetaData(); // Print the meta data int NCols = meta.getColumnCount(); // # of attributes in result System.out.println ("Name Type DispSz Scale Precis ClassName"); System.out.println ("-----------------------------------------------"); for (int i = 1; i <= NCols; i++) { System.out.println (meta.getColumnName(i) + "\t" + meta.getColumnType(i) + "\t" + meta.getColumnTypeName(i) + "\t" + meta.getColumnDisplaySize(i) + "\t" + meta.getScale(i) + "\t" + meta.getPrecision(i) + "\t" + meta.getColumnClassName(i) + "\t" ); } conn.close(); } catch (Exception e) { System.out.println("Error: " + e.getMessage() ); // Print error message } } } |
How to run the program:
|
Types codes: String: 1 (Type codes obtained from: java.lang.Types class) INT: 4 DECIMAL: 3 Name TypeCode TypeName DispSz Scale Precis ClassName --------------------------------------------------------------------- fname 1 CHAR 6 0 6 java.lang.String minit 1 CHAR 1 0 1 java.lang.String lname 1 CHAR 8 0 8 java.lang.String ssn 1 CHAR 9 0 9 java.lang.String bdate 1 CHAR 10 0 10 java.lang.String address 1 CHAR 25 0 25 java.lang.String sex 1 CHAR 1 0 1 java.lang.String salary 3 DECIMAL 9 2 7 java.math.BigDecimal superssn 1 CHAR 9 0 9 java.lang.String dno 4 INT 11 0 11 java.lang.Integer |