In this section we will discuss how can we find out the total number of columns from a specified table.
Find the number of columns using servlet
In this section we will discuss how can we find out the total number of columns from a specified table.
At first we should have a table, so I created a table named dataformat in a database formRecord.mdb. Now in java program I created a class named GetColumnNumber which extends the HttpServlet class. In the body of the class I defined the doGet() method into which I used the getWriter() method of HttpServletResponse for writing on browser. Then uses the classes of java.sql package for establishing the database connection, creating statement, executing SQL statement etc. To count the total number of columns in a table I use the getColumnCount() method of ResultSetMetaData interface. Before using the getColumnCount() method it should be understand that the ResultSet interface retrieves the number of columns and its properties using getMetaData() method and returns it into the ResultSetMetaData from where the getColumnCount() method finds column number.
Example :
GetColumnNumber.java
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetColumnNumber extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); Connection con; PreparedStatement ps; ResultSet rs; ResultSetMetaData rsmd; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con= DriverManager.getConnection("jdbc:odbc:formRecord"); ps= con.prepareStatement("SELECT * FROM dataformat"); rs= ps.executeQuery(); rsmd = rs.getMetaData(); int i = rsmd.getColumnCount(); pw.println("There are "+i+" columns in table '"+rsmd.getTableName(i)+"'"); } catch(Exception e) { pw.println(e); } } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>GetColumnNumber</display-name> <servlet> <servlet-name>GetColumnNumber</servlet-name> <servlet-class>GetColumnNumber</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetColumnNumber</servlet-name> <url-pattern>/GetColumnNumber</url-pattern> </servlet-mapping> </web-app>
Output :
At first I have created a database with the field like this
When you will execute the above example you will find the following output:
[ 0 ] Comments