+8 votes
30.9k views
in Programming by (960 points)
i want to print table of database this query result is giving row count but i want to know how can i print the all column and row of that table.
closed

1 Answer

+1 vote
by Expert (5.9k points)
selected by
 
Best answer

see this code here i have used a query and print all data from database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class test1 {
public static void main(String args[]) {
Statement stmt = null;
Connection conn = null;
try{ 
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection
("jdbc:jtds:sqlserver://servername:1433/DB","username","password");
Statement stmt1 =conn.createStatement();
ResultSet rs = stmt1.executeQuery("select * from table where USERID='admin';");
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
 
      System.out.println("");
 
     int numberOfColumns = rsmd.getColumnCount();
 
     for (int i = 1; i <= numberOfColumns; i++) {
       if (i > 1) System.out.print(",  ");
       String columnName = rsmd.getColumnName(i);
       System.out.print(columnName);
     }
     System.out.println("");
 
     while (rs.next()) {
       for (int i = 1; i <= numberOfColumns; i++) {
         if (i > 1) System.out.print(",  ");
         String columnValue = rs.getString(i);
         System.out.print(columnValue);
       }
       System.out.println("");  
     }
 
    
     conn.close();
 
  }catch(SQLException se){
     //Handle errors for JDBC
     se.printStackTrace();
  }catch(Exception e){
     //Handle errors for Class.forName
     e.printStackTrace();
  }finally{
     //finally block used to close resources
     try{
        if(stmt!=null)
           stmt.close();
     }catch(SQLException se2){
     }// nothing we can do
     try{
        if(conn!=null)
           conn.close();
     }catch(SQLException se){
        se.printStackTrace();
     }//end finally try
  }//end try
  System.out.println("Goodbye!");
}
}
0
by (960 points)
himanshu thanks,nice work!
0
by Expert (5.9k points)
Pleasure of mine :)

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated