INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

How do I create a database class for an application

How do I create a database class for an application

How do I create a database class for an application

(OP)
Hi All,

I'm sure I'm asking the most basic of questions, so sorry if this seems to be the very basics. I am trying my best to learn Java....

I have an access database which for example is called "myDB.mdb".

I can access this database from a class that I have written to output a simple select to the console.

To my understanding, in a larger application I should place database connections into a separate class so I can reference this class to access the database.

I have spent a few days on Google trying to understand how to do this, but all it shows me is how to create the simple connection I  have already done.

Am I looking at this in the right way??

Can anyone give me some code to both a) setup the class file and b) an example of how to reference it from a different class.

I have tried to do the following, but it doesn't work properly, so this could be a starting point:

getConnection.java

CODE


package Database;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;

public abstract class getConnection implements Connection {
    
    public static Connection getConnection() throws Exception {
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        //String url = "jdbc:odbc:northwind";
        String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\\myDB.mdb;}";
        String username = "admin";
        String password = "";
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

}

frmLogon.java

CODE


package Forms;

import java.awt.EventQueue;


public class frmLogon {

    private JFrame frmLogon;
    private JTextField txtUserID;
    private JPasswordField txtPassword;
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frmLogon window = new frmLogon();
                    window.frmLogon.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public frmLogon() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmLogon = new JFrame();
        frmLogon.setTitle("Logon");
        frmLogon.setBounds(100, 100, 253, 171);
        frmLogon.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmLogon.getContentPane().setLayout(null);
        
        txtUserID = new JTextField();
        txtUserID.setBounds(77, 11, 152, 20);
        frmLogon.getContentPane().add(txtUserID);
        txtUserID.setColumns(10);
        
        txtPassword = new JPasswordField();
        txtPassword.setBounds(77, 42, 152, 20);
        frmLogon.getContentPane().add(txtPassword);
        
        JLabel lblUserId = new JLabel("User ID:");
        lblUserId.setBounds(10, 14, 57, 14);
        frmLogon.getContentPane().add(lblUserId);
        
        JLabel lblPassword = new JLabel("Password:");
        lblPassword.setBounds(10, 42, 57, 14);
        frmLogon.getContentPane().add(lblPassword);

        final JLabel lblError = new JLabel(" ");
        lblError.setHorizontalAlignment(SwingConstants.CENTER);
        lblError.setForeground(Color.RED);
        lblError.setBounds(10, 73, 219, 14);
        frmLogon.getContentPane().add(lblError);
        
        JButton btnLogon = new JButton("Logon");
        btnLogon.addMouseListener(new MouseAdapter() {
            @Override
            
            public void mouseClicked(MouseEvent arg0) {
                
            char[] strPassword = txtPassword.getPassword();
                
            if(txtUserID.getText().equals("")||txtUserID.getText().equals(null))
                {
                    System.out.println("No User ID");
                    lblError.setText("Please Enter A User ID");
                    return;
                }
            else
                {
                    if(strPassword.length==0)
                        {
                            System.out.println("No Password");
                            lblError.setText("Please Enter A Password");
                            return;
                        }
                    else
                        {
                            /*if(new String (txtPassword.getPassword()).equals("MyPassword"))
                            {
                                System.out.println("This is the value: xx" + txtUserID.getText() + "xx");
                                System.out.println("System Logon");
                                lblError.setText("  ");
                            }
                            else
                            {
                                System.out.println("This is the value: xx" + txtUserID.getText() + "xx");
                                lblError.setText("Invalid Password");
                                return;
                            } */
                        }
                }
            
            /// Insert DB Try Here
            System.out.println( "Path is " + System.getProperty("java.class.path()"));
            
            Connection conn = getConnection();
            Statement st = conn.createStatement();

            ResultSet rs = st.executeQuery("SELECT * FROM tblUsers");

            ResultSetMetaData rsMetaData = rs.getMetaData();

            int numberOfColumns = rsMetaData.getColumnCount();
            System.out.println("resultSet MetaData column Count=" + numberOfColumns);

            st.close();
            conn.close();
            }


        });
        
        btnLogon.setBounds(20, 98, 89, 23);
        frmLogon.getContentPane().add(btnLogon);
        
        JButton btnQuit = new JButton("Quit");
        btnQuit.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                System.exit(0);
            }
        });
        btnQuit.setBounds(119, 98, 89, 23);
        frmLogon.getContentPane().add(btnQuit);

    }
}


Many thanks for any help you can give me,

Regards,

Fitz

Fitz
Did you know, there are 10 types of people in this world:
* Those who understand binary
  and
* Those who Don't!!

RE: How do I create a database class for an application

First of all, by convention class names start with capital letter and you should use a name like ConnectionManager instead of getConnection for your database class


Well, in your case, instead of

CODE

Connection conn = getConnection();
a simple

CODE

Connection conn = getConnection.getConnection();

You will also need an

CODE

import Database.getConnection;
sentence.

Meanwhile, this may help you to understand method calls

Cheers,
Dian

RE: How do I create a database class for an application

(OP)
Hi Dian,

That's bang on!!! I now know a little more. It's slowly stating to make sense, but more importantly, I understand how to use a common class. . . .

I am now sorting out the class names as suggested. I did know about naming conventions, however, I think I may have been a little confused when I started putting it together.

I've jsut had a little test of it and it seems to be working within the expected results, which admittedly isn't a lot!!

Thanks so much for your help,

Regards,

Fitz

Fitz
Did you know, there are 10 types of people in this world:
* Those who understand binary
  and
* Those who Don't!!

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close