package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class JDBCConnection {
	public static void main(String[] args) {
		stmt_readData("select * from sample");
	}

	
	//Connect to DB and execute query using Statement interface
	static void stmt_readData(String strQueury) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet res = null;
		ResultSetMetaData resMeta = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "tiger");
			stmt = conn.createStatement();
			res = stmt.executeQuery(strQueury);
			resMeta = res.getMetaData();
			
			//column names
			int count = resMeta.getColumnCount();
			for(int i=1; i<=count; i++) {
				System.out.print(resMeta.getColumnName(i)+"     ");
			}
			System.out.println();
			
			
			//Read the table data
			while(res.next() == true) {
				for(int i=1; i<=count; i++) {
					System.out.print(res.getString(resMeta.getColumnName(i))+"     ");
				}
				System.out.println();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		finally
		{
			try {
				resMeta = null;
				res.close();
				res = null;
				stmt.close();
				stmt = null;
				conn.close();
				conn = null;
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}
