Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I create a database class for an application 1

Status
Not open for further replies.

TheFitz

Programmer
Dec 18, 2003
140
GB
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!!
 
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
 
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!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top