Hey there! any question in your mind? Ask It Now!.

Popular Categories





How can i print table data with query result ?

+8 votes
88 views
asked in Programming by raghav (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.

1 Answer

+1 vote
answered by Himanshu Expert (5,940 points)
selected by raghav
 
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!");
}
}
commented by raghav (960 points)
himanshu thanks,nice work!
commented by Himanshu Expert (5,940 points)
Pleasure of mine :)

Related Questions

+12 votes
1 answer 111 views
+8 votes
2 answers 106 views
+1 vote
1 answer 950 views
+1 vote
0 answers 91 views
+6 votes
1 answer 127 views
+2 votes
1 answer 863 views
+2 votes
1 answer 88 views
+2 votes
1 answer 95 views
+2 votes
1 answer 53 views
asked in Programming by neha (560 points)
0 votes
0 answers 432 views

Not a Member yet?

Ask to Folks Login

My Account
1068 Folks are online
68 members and 1000 guest online
Your feedback is highly appreciated