Simple GUI database driven application
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: Simple GUI database driven application

  1. #1
    Join Date
    Nov 2009
    Posts
    4

    Simple GUI database driven application

    i have to develop a simple GUI based database driven application for Bank system.
    and required to use MS Access to create a database named Bank and add a table named Account into this database.
    The Account table must have following fields:
    1. Account Number
    2. Account Holder Name
    3. Account Type
    4. Account Balance

    You must enter 10 records within Account table of Bank database.
    Create a system DSN (Data Source Name) named bankDSN and use this DSN in a program to connect to this database.
    Write a program which will have following functionalities:
    1) A method which will have the functionality to connect to database.

    2) A method which will retrieve all the records of user from database and display on GUI window. The top header of GUI window must have columns name of table Account. The column names displayed on GUI must be same as columns name within table of database. You have to use ResultSetMetaData object for this purpose. You cannot use hard coded values to display columns name.

    The above method will connect to this database and query all the records from the “Account” table using SQL statement and display them on GUI application.
    You can use Grid Layout to display the records from database to GUI application.
    You must use ResultSetMetaData to display exact name of columns of database table on the top of GUI application. Marks will be deducted in case of not using ResultSetMetaData.


    i have written the code but it have many errors and i cant figure them out because i have very short time

    here am posting my code please help me out in this regard i will be very helpful to you peoples

    Code:
    package bank;
    public class Main {
        public static void main(String[] args) {
            
        }
    
    }
    
    public class NewJFrame extends javax.swing.JFrame {
    
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
        }
    
        
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            Bank = new javax.swing.JLabel();
            jTextField = new javax.swing.JTextField();
            button = new java.awt.Button();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            Bank.setFont(new java.awt.Font("Palatino Linotype", 3, 12)); // NOI18N
            Bank.setText("Bank");
    
            button.setLabel("Click Me To Show Accounts Detail");
            button.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(178, 178, 178)
                            .addComponent(Bank, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(38, 38, 38)
                            .addComponent(jTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(98, 98, 98)
                            .addComponent(button, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(41, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(Bank, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(button, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(99, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
            
    import java.sql.*;
    public class MetaDataEx {
    public static void main (String args[ ]) {
    try {
    //Step 2: load driver
    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
    //Step 3: define the connection URL
    String url = “jdbc:odbc:BankDSN”;
    //Step 4: establish the connection
    Connection con = null;
    con = DriverManager.getConnection(url, “”, “”);
    //Step 5: create PrepareStatement by passing sql and
    // ResultSet appropriate fields
    String sql = “SELECT * FROM Bank”;
    PreparedStatement pStmt = con.prepateStatement(sql,
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    //Step 6: execute the query
    ResultSet rs = pStmt.executeQuery();
    // get ResultSetMetaData object from rs
    ResultSetMetaData rsmd = rs.getMetaData( );
    // printing no. of column contained by rs
    int numColumns = rsmd.getColumnCount();
    System.out.println(“Number of Columns:” + numColumns);
    // printing all column names by using for loop
    String cName;
    for(int i=1; i<= numColumns; i++) {
    cName = rsmd.getColumnName(i);
    System.out.println(cName);
    System.out.println(“\t”);
    }
    // changing line or printing an empty string
    System.out.println(“ ”);
    // printing all values of ResultSet by iterating over it
    String id, name, add, ph;
    while( rs.next() )
    {
    CustomerName = rs.getString(1);
    AccountNo = rs.getString(2);
    AccountType = rs.getString(3);
    DateOpened = rs.getString(4);
    Balance = rs.getString(5);
    System.out.println(CustomerName);
    System.out.println(“\t”);
    System.out.println(AccountNo);
    System.out.println(“\t”);
    System.out.println(AccountType);
    System.out.println(“\t”);
    System.out.println(DateOpened);
    System.out.println(“\t”);
    System.out.println(Balance);
    System.out.println(“ ”);
    }
    //Step 8: close the connection
    con.close();
    }catch(Exception sqlEx){
    System.out.println(sqlEx);
    }
     } // end main
    } // end class
    }
    
        
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify
        private javax.swing.JLabel Bank;
        private java.awt.Button button;
        private javax.swing.JTextField jTextField;
        // End of variables declaration
    
    }

  2. #2
    Join Date
    Apr 2007
    Posts
    425

    Re: Simple GUI database driven application

    Quote Originally Posted by iishiii View Post
    i have written the code but it have many errors and i cant figure them out because i have very short time
    Procrastination sucks, doesn't it. Ask for help sooner; you threw a wall of text, some code, and didn't even bother to specify what errors you encountered and where you got stuck.
    ------
    If you are satisfied with the responses, add to the user's rep!

  3. #3
    Join Date
    Jun 2007
    Location
    Aurora CO USA
    Posts
    137

    Red face Re: Simple GUI database driven application

    While I agree with Deliverance (don't wait until you're desperate for time and tell us what errors you're seeing), some things jump out at me right away:

    1. I'm assuming that this is one source file. If so, why does it contain multiple public classes? From the Java Tutorial(http://java.sun.com/docs/books/tutor...reatepkgs.html):
    "If you put multiple types in a single source file, only one can be public, and it must have the same name as the source file. For example, you can define public class Circle in the file Circle.java, define public interface Draggable in the file Draggable.java, define public enum Day in the file Day.java, and so forth.

    You can include non-public types in the same file as a public type (this is strongly discouraged, unless the non-public types are small and closely related to the public type), but only the public type will be accessible from outside of the package. All the top-level, non-public types will be package private. "
    2. What is the point of class Main? It does nothing and has a main method that does nothing.
    3. Why are you using nested classes (i.e. one class inside another)? This seems unnecessary.
    4. By convention, import statements are consigned to the top of the source file (where they are immediately visible and easy to locate).
    5. With buttonActionPerformed, you've defined a method (in a class), with a class, which has a main method, which is never used.
    6. You're continually using System.out.println() when it's obvious you mean System.out.print(). This would be a moot point, however, since your program is apparently supposed to be a GUI program and print/println output to the command line.
    7. Near the end of the code, your third(!) main method. This seems to be the only valid one.
    8. At the end of your code are variables. You should probably consider what your instructor wants you to do with them.

    Basically, I wonder if you've attended any of the classes relating to this exercise. You seem to have no idea of correct program structure or flow of execution for java. It's not magic. You can't just throw random code into a source file and expect the compiler to know what you want to do.

    I'd advise you to do the following:
    1. Review your textbook or the Java Tutorial on basic program/object construction.
    2. Plan out what your program needs to do. This step is very important and you definitely shouldn't skip it, especially as a beginner.
    3. Write your code, testing as you go. If you churn out hundreds of lines of incorrect code (as you have now), correcting it is all that much harder. Work in small logical steps.
    4. Be logical. Remember logic is the key to how a computer works.
    5. When you have something concrete that isn't working or is giving you errors you don't understand, post here with the complete code, the full error or exception text, and your specific questions.

    No one here is going to do your homework for you. It is your exercise to help you learn. Most of the people here are volunteers who don't have time to take your code and build it to see what compile/runtime errors are produced; you need to provide specific error messages and questions for them to answer.

    Best Regards,
    alan
    Last edited by ajhampson; November 24th, 2009 at 10:55 AM. Reason: submitted too early.

  4. #4
    Join Date
    Apr 2007
    Posts
    425

    Re: Simple GUI database driven application

    Quote Originally Posted by ajhampson View Post
    4. By convention, import statements are consigned to the top of the source file (where they are immediately visible and easy to locate).
    it is not by convention, but a compile requirement that importing a package member must appear after the package definition, and precede any class definition.
    ------
    If you are satisfied with the responses, add to the user's rep!

  5. #5
    Join Date
    Jun 2007
    Location
    Aurora CO USA
    Posts
    137

    Re: Simple GUI database driven application

    Yup, that's what I should have said. 8-)

    Thanks D!

    alan

  6. #6
    Join Date
    Nov 2009
    Posts
    4

    Re: Simple GUI database driven application

    kindly check this code for above mentions problem which also having error and not going to be compiled please find out the error and make me clear about error i will be very thank full to u peoples

    Code:
    // importing packages
    
    	import java.awt.*;
    	import java.io.*;
    	import javax.swing.*;
    	import java.sql.*;
    				// defining class BankSystem
    
    	public class BankSystem{
    	private JFrame frame;
    	private Container cont ;
    	private Connection dbCon ;
    	private Statement st ;
    	private ResultSet resultSet ;
    	private ResultSetMetaData rsmd ;
    
    		// constructor
    
    	public BankSystem(){
    		connection() ;
    		displayData() ; // Showing Accout Table Data on Window
    	}
    		// method that retrieving data from database & showing on GUI
    
    	public void displayData(){
    	frame = new JFrame();
    	cont = frame.getContentPane();
    try{
    
    	String sql = "SELECT * FROM Account"; 		// SQL select statement 
    	res0ultSet = st.executeQuery(sql);		// execute the SQL statement
    	rsmd = resultSet.getMetaData(); 
    	int columns = rsmd.getColumnCount(); 
    	resultSet.last(); 
    	int rows = resultSet.getRow() + 1 ; // returns the index of last row and adding 1
    	cont.setLayout(new GridLayout(rows,columns)); 
    	for (int i =1 ; i<= columns; i++)
    	{
    
    
    							// Adding columns names to Frame
    
    	cont.add(new JLabel(rsmd.getColumnName(i)));
    	}
    	resultSet.first();
    	while (resultSet.next()){ 
    	JLabel label1 = new JLabel(resultSet.getString(1)); 	// Setting field value
    	JLabel label2 = new JLabel(resultSet.getString(2)); 	// Setting field value 
    	JLabel label3 = new JLabel(resultSet.getString(3)); 	// Setting field value
    	JLabel label4 = new JLabel("" + resultSet.getInt(4)); 	// Setting field value 
    	cont.add(label1); 				// Adding label1 
    	cont.add(label2); 				// Adding label2
    	cont.add(label3); 				// Adding label3 
    	cont.add(label4); 				// Adding label4
    	}
    	dbCon.close(); 
    	}catch(Exception sqlEx){ 
    	System.out.println(sqlEx); 
    	}
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    	frame.setSize(400,500); 		// Size of the Window
    	frame.setVisible(true); 		// Displaying Window On Screen
    	frame.setResizable(false); 		// Stoping Window from resizing
    	}
    
    					// method that create a connection to database
    		
    	public void connection()
    	{
    
    try{
    	Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    	String url = "jdbc:odbc:bankDSN";
    	dbCon = DriverManager.getConnection(url); 		// COnnection establish
    	st = dbCon.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 					ResultSet.CONCUR_UPDATABLE);
    
    	}catch(Exception sqlEx){ 
    	System.out.println(sqlEx); 				// exception print on screen
    
    	}
    	} 							// end of connection method
    
    	public static void main(String args[]){
    	BankSystem a = new BankSystem();
    	}							// main end
    
    	} 							// class end

  7. #7
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    Re: Simple GUI database driven application

    Please supply the output from running the Java compiler so we can see what and where the errors are.

  8. #8
    Join Date
    Nov 2009
    Posts
    4

    Re: Simple GUI database driven application

    While Compiling it these errors are coming


    ======================================

    C:\Program Files\Java\jdk1.6.0_14\bin>javac Ishtiaq.java
    Ishtiaq.java:10: class BankSystem is public, should be declared in a file named
    BankSystem.java
    public class BankSystem{
    ^
    Ishtiaq.java:32: cannot find symbol
    symbol : variable res0ultSet
    location: class BankSystem
    res0ultSet = st.executeQuery(sql); // execute the SQL stat
    ment
    ^
    2 errors

    C:\Program Files\Java\jdk1.6.0_14\bin>

    ===========================================================

  9. #9
    Join Date
    Jun 2007
    Location
    Aurora CO USA
    Posts
    137

    Re: Simple GUI database driven application

    Code:
    C:\Program Files\Java\jdk1.6.0_14\bin>javac Ishtiaq.java
    Ishtiaq.java:10: class BankSystem is public, should be declared in a file named
    BankSystem.java
    public class BankSystem{
    ^
    Ishtiaq.java:32: cannot find symbol
    symbol : variable res0ultSet
    location: class BankSystem
    res0ultSet = st.executeQuery(sql); // execute the SQL statment
    ^
    2 errors

    I think you just need to read the errors (apologies in advance if English as a second language is causing you difficulty with this).

    Error 1 says that your Public Class BankSystem should be in a file named BankSystem.java. This is due to the rule I posted yesterday that says "If you put multiple types in a single source file, only one can be public, and it must have the same name as the source file." Simply rename your source file from Ishtiaq.java to BankSystem.java and this error will go away.

    For error 2, look closely at the name of the variable it says it can't find (note that the carat ^ is positioned below the problem the compiler noted): res0ultSet. Looking at your source, you haven't declared a variable named res0ultSet, bur you do have one named resultSet which is probably what you need to change the variable on line 32 to.

    Make these two changes and try the compile again. If you get errors or exceptions you don't understand, please let us know.

    BTW, this code looks much better than your first post.

    alan

  10. #10
    Join Date
    Nov 2009
    Posts
    4

    Re: Simple GUI database driven application

    I have Done it

    Thank you Very Much My friend

    Thank you Very Much a Bundle of Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center