Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Cannot connect to MS Access Database :(

  1. #1
    Junior Member
    Join Date
    Mar 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Cannot connect to MS Access Database :(

    Hello everyone,

    I am new to Java programming. I found a gui which connects to a MS Database. I also have the database file, but I am not sure about how to connect this gui with the database. Can somebody explain it to me? Thanks in advance... :$

    //Java Core Package
    import javax.swing.*;
    //Java Extension Package
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
     
    public class addItemToDatabase extends JFrame {
     
    	//Initializing Components
    	private JTextField inputs[];
    	private JButton add, reset;
    	private JLabel labels[];
    	private String fldLabel[] = {"First Name: ","Middle Name: ","Family Name: ","Age: "};
    	private JPanel p1;
     
    	Connection con;
    	Statement st;
    	ResultSet rs;
    	String db;
     
    	//Setting up GUI
        public addItemToDatabase() {
     
        	//Setting up the Title of the Window
        	super("Adding Data to the Database");
     
        	//Set Size of the Window (WIDTH, HEIGHT)
        	setSize(300,180);
     
        	//Exit Property of the Window
        	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		//Constructing Components
        	inputs = new JTextField[4];
        	labels = new JLabel[4];
        	add = new JButton("Add");
        	reset = new JButton("Reset");
        	p1 = new JPanel();
     
        	//Setting Layout on JPanel 1 with 5 rows and 2 column
        	p1.setLayout(new GridLayout(5,2));
     
        	//Setting up the container ready for the components to be added.
        	Container pane = getContentPane();
        	setContentPane(pane);
     
        	//Setting up the container layout
        	GridLayout grid = new GridLayout(1,1,0,0);
        	pane.setLayout(grid);
     
        	//Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
        	try {
    				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    				db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
    				con = DriverManager.getConnection(db,"","");
    				st = con.createStatement();		
     
    				JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
     
    			} catch (Exception e) {
    				JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
    				System.exit(0);
    			}
     
        	//Constructing JLabel and JTextField using "for loop" in their desired order
        	for(int count=0; count<inputs.length && count<labels.length; count++) {
        		labels[count] = new JLabel(fldLabel[count]);
        		inputs[count] = new JTextField(20);
     
        		//Adding the JLabel and the JTextFied in JPanel 1
        		p1.add(labels[count]);
        		p1.add(inputs[count]);
        	}
     
        	//Implemeting Even-Listener on JButton add
    		add.addActionListener(
    		new ActionListener() {
     
    			//Handle JButton event if it is clicked
    			public void actionPerformed(ActionEvent event) {
     
    				if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
    					JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
     
    				else
     
    				try {
     
    					String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
    					st.execute(add); //Execute the add sql
     
    					Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
     
    					JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
     
    				}catch (NumberFormatException e) {
    					JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
    				}catch (Exception ei) {
    					JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
    				}
    			}
    		}
    		);
     
    		//Implemeting Even-Listener on JButton reset
    		reset.addActionListener(
    		new ActionListener() {
     
    			//Handle JButton event if it is clicked
    			public void actionPerformed(ActionEvent event) {
    				inputs[0].setText(null);
    				inputs[1].setText(null);
    				inputs[2].setText(null);
    				inputs[3].setText(null);
    			}
    		}
    		);
     
    		//Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
    		p1.add(add);
    		p1.add(reset);
     
    		//Adding JPanel 1 to the container
    		pane.add(p1);
     
        	/**Set all the Components Visible.
        	 * If it is set to "false", the components in the container will not be visible.
        	 */
        	setVisible(true);
        }
     
    	//Main Method
        public static void main (String[] args) {
        	addItemToDatabase aid = new addItemToDatabase();
    	}
    }


  2. #2
    Junior Member
    Join Date
    Jan 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cannot connect to MS Access Database :(

    The relevant part is
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement();

    JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    }
    You need an Access database named AddItemDB.mdb.

  3. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cannot connect to MS Access Database :(

    check ur DSN name

    --- Update ---

    please give valid DSN name

  4. #4
    Junior Member
    Join Date
    Jan 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cannot connect to MS Access Database :(

    in getConnection() method just write like this..
    DriverManager.getConnection("jdbcdbc:dsn _name");

    just provide ur dsn name correctly..ur application vl work properly..
    good luck..

Similar Threads

  1. Replies: 21
    Last Post: November 27th, 2012, 10:58 PM
  2. Cant connect with database
    By ronn1e in forum JDBC & Databases
    Replies: 1
    Last Post: January 4th, 2011, 05:45 PM
  3. Replies: 6
    Last Post: August 18th, 2010, 05:41 PM