-1

I have made a MySql database and connected it using JDBC connector to my java project.

This is my database schema:

This is my customers table:

I have successfully fetched the data from the table 'customers' using this query:

SELECT * FROM zahirdb.customers;

This is the output that I am getting.

But I also want to print the column names too, I have found out the solution code which is running in mySQL workbench but when i try to run that same solution code, I'm getting exceptions. These are the exceptions I'm gettng

This is the solution that I found:

SELECT 'id', 'name', 'age', 'order_id' UNION SELECT * FROM zahirdb.customers;

This statement is generating errors in my java program but when I am executing it in MySQL workbench, its working perfectly fine there and printing column names too. But I want to print the column names too along with data in my java output console. Kindly help me.

This is my java program code:

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Zahir
 */
public class displayInfo {

    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            //Logger.getLogger(displayInfo.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("mysql driver not found");
        }
        
        Connection conn = null;
        try {
            conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/zahirdb","root","admin");
            System.out.println("Connection successfull");
            
            //String query = "SELECT 'id', 'name', 'age', 'order_id' UNION SELECT * FROM    
            //zahirdb.customers;";

            String query = "SELECT * FROM zahirdb.customers;";
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(query);
            
            System.out.println("\nQuery Running:" + query);
            System.out.println("\nQuery Result:");
            
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                int o_id = rs.getInt("order_id");
                
                System.out.println(id +" "+ name +" "+ age +" "+ o_id);
            }
            st.close();
        } catch (SQLException ex) {
            Logger.getLogger(displayInfo.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Connection failed");
        }
        finally{
            try{
                if(conn!=null){
                    System.out.println("\nClosing connection");
                    conn.close();
                }
            }
            catch(SQLException e){
                e.printStackTrace();
            }
        
        }
    
}
    
}

0 Answers0