Java NetBeans connecting to MS Access Database Error

1.4k Views Asked by At

That's my program: This picture shows the whole program. Please see this link. Thank you!

Cannot Connect. Details below. Please help me! Thanks!

This is my code in "Java Class" (Connect)

import java.sql.*;
import javax.swing.*;

public class Connect {
Connection conn = null;
ResultSet rst = null;
PreparedStatement pst = null;

public static Connection ConnectDB(){
try{Class.forName ("sun.jbdc.odbc.JbdcOdbcDriver");

Connection conn=DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver(*.mdb)}; DBQ = Data.mdb");

JOptionPane.showMessageDialog(null, "Connected");
return conn;
}catch(Exception e){JOptionPane.showMessageDialog(null, "not connected");
return null;
}
}
}

While this are my code in "NewJFrame"

In this NewJFrame. I used the import java.sql.*; and connection conn to connect it from the "public static Connection ConnectDB()" from the "Java Class (Connect)". I just used a event that is WindowedOpen to atleast try if its connected. But sad to say. Its not. Please help me! Hoping for good and easy to understand answers.

import java.sql.*;
public class NewJFrame extends javax.swing.JFrame {
Connection conn = null;

public NewJFrame() {
        initComponents();
    }

@SuppressWarnings("unchecked")

 private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
   conn = Connect.ConnectDB();
    }        

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
1

There are 1 best solutions below

0
kyoya007 On

First Try to correct your coding

Number 1

try{Class.forName ("sun.jbdc.odbc.JbdcOdbcDriver");

to

try{Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

then when the above still does not work try to path the MS Access

Number 2
From

DBQ = Data.mdb

to

DBQ = 'path'/Data.mdb

Ex.: path = 'D:\DB\MSAccess\' + Data.mdb | D:\DB\MSAccess\Data.mdb