How to get Total Columns Returned by Query

 ResultSet rs = stmt.executeQuery(strSQL);
 ResultSetMetaData rsmd = rs.getMetaData();
 int columnsNumber = rsmd.getColumnCount();

How to get Column Name from Query

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 String name = rsmd.getColumnName(1);

How to get Column Count from Query and Loop Through That

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
  String name = rsmd.getColumnName(i);
  // Do stuff with name
}

To Find a Column with particular Name

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 rs.getString(rs.findColumn("fullname"));

How to get List of Column Names from Query and Store it in a Array

 ResultSetMetaData meta = resultset.getMetaData();  
 Integer columncount = meta.getColumnCount();
 int count = 1 ; 
 String[] columnNames = null;

 while(columncount <=count)
  columnNames [i] = meta.getColumnName(i);

 System.out.println (columnNames.size());

The Servlet which loads the Singleton class should be loaded during the server startup

ConfigServlet.java

public class ConfigServlet extends HttpServlet
{	
	@Override
	public void init() throws ServletException
	{
	  super.init();
	  SingletonDBConnection.getInstance();
	}
}

web.xml

<servlet>
   <servlet-name>StartUpServlet</servlet-name>
   <servlet-class>com.mugil.tutor.ConfigServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

DBConnection.java

public class DBConnection
{
	public Connection getDBConnection()
	{
		Connection connection = null;

		try
		{
			connection = DriverManager.getConnection(
					"HOST_NAME", "USER_NAME", "PASSWORD");

		}
		catch (SQLException e)
		{
			e.getLocalizedMessage();	
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return null;
		}
		return connection;
	}
}

SingletonDBConnection.java

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class SingletonDBConnection
{
	private static SingletonDBConnection singleInstance;
	private static DataSource dataSource;
	private static Connection dbConnect;
	
	private SingletonDBConnection()
	{
		try
		{
			Context initContext = new InitialContext();
			Context envContext  = (Context) initContext.lookup("java:/comp/env");
			dataSource		   = (DataSource) envContext.lookup("jdbc/testdb");
			
			try
			{
				dbConnect  = dataSource.getConnection();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			} 	
		}
		catch (NamingException e)
		{
			e.printStackTrace();
		}
	}
	
	public static SingletonDBConnection getInstance()
	{
		if(singleInstance == null)
		{
			synchronized (SingletonDBConnection.class)
			{
				if(singleInstance == null)
				{
					singleInstance = new SingletonDBConnection();
				}
			}
		}

		return singleInstance;
	}
	
	public static Connection getConnInst()
	{
		try
		{
			dbConnect = dataSource.getConnection();
		}
		catch (SQLException e1)
		{
			e1.printStackTrace();
		}
		
		if(dbConnect == null)
		{
			try
			{
				Context initContext = new InitialContext();
				Context envContext  = (Context) initContext.lookup("java:/comp/env");
				dataSource		    = (DataSource) envContext.lookup("jdbc/testdb");
				
				try
				{
					dbConnect  = dataSource.getConnection();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				} 	
			}
			catch (NamingException e)
			{
				e.printStackTrace();
			}
		}
		
		return dbConnect;		 
	}
}

ListUsers.java

public List<User> getUsersList()
	{
		Connection conn;
		Statement  stmt = null;
		ResultSet  rs;
		List<User> arrUsersList = new ArrayList<User>();
		conn = SingletonDBConnection.getInstance().getConnInst();
		
		String strSQL = "SELECT UserId, UserName, Gender, UserLocation " +
						"  FROM tblusers";
		
		try
		{
			stmt = conn.createStatement();			
			rs = stmt.executeQuery(strSQL);
			
			while(rs.next())
			{
				User objUser = new User();
				objUser.setUserId(rs.getString("UserId"));
				objUser.setUserName(rs.getString("UserName"));
				objUser.setUserGender(rs.getString("Gender"));
				objUser.setUserLocation(rs.getString("UserLocation"));
				arrUsersList.add(objUser);
			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
		}
		
		
		return arrUsersList;
	}

How to Avoid unnessecary HTML Code while generating HTML for Mail or HTML File

Method1

DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName));

dosReport.wrtiteBytes("<table><thead>");

dosReport.writeBytes("<th>Column1</th>");
dosReport.writeBytes("<th>Column2</th>");
dosReport.writeBytes("<th>Column3</th>");
dosReport.writeBytes("<th>Column4</th>");
dosReport.writeBytes("<th>Column5</th>");
dosReport.writeBytes("<th>Column6</th>");
dosReport.writeBytes("<th>Column7</th>");
dosReport.writeBytes("<th>Column8</th>");
dosReport.writeBytes("<th>Column9</th>");

dosReport.wrtiteBytes("</thead>");

Method2
Replace with Below


DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName));
dosReport.wrtiteBytes("<table><thead>");

String[] columns = {"Column1", "Column2", "Column3", 
                    "Column4", "Column5", "Column6", 
                    "Column7", "Column8", "Column9"};

for(int i = 0; i < columns.length; i++)
 dosReport.writeBytes("<th>" + columns[i] +"</th>");

dosReport.wrtiteBytes("</thead>");

Disadvantage:
In the Method1 you have fine control over individual cell(tds) so you can add properties like align, individual stylings can be applied.

The below code reads a Sample.txt file and places the content in a newly created Html file Sample.html.

The file from which the content should be read is placed in a project directory which is printed in the console using the below java code.

System.out.println("Working Directory = " + System.getProperty("user.dir"));

The above code prints the current project directory in console.

package com.mugil.servlets;

import java.awt.Desktop;
import java.io.*;

class GenerateHTML 
{
    public static void main(String[] args) throws Exception 
    {    	
    	System.out.println("Working Directory = " +
                System.getProperty("user.dir"));
        BufferedReader br = new BufferedReader(new FileReader("Sample.txt"));
        File f = new File("source.htm");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("<html>");
        bw.write("<body>");
        bw.write("<h1>ShowGeneratedHtml source</h1>");

        String line;
        while ((line=br.readLine())!=null) {
            bw.write(line);
            bw.newLine();
        }        
        bw.write("</body>");
        bw.write("</html>");

        br.close();
        bw.close();

        Desktop.getDesktop().browse(f.toURI());
    }
}

executeupdate vs executequery vs execute

ResultSet executeQuery() – Used for reading the content of the database.
output will be in form of ResultSet.
eg – SELECT statement.

int executeUpdate() – Used for DML(altering the database).
output will be in int.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

boolean execute() – Executing SQL statements.
output will be in boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.