Carsh CaNe Carsh CaNe - 6 months ago 52
Java Question

I can't connect to MS Access with Java Eclipse

I'm trying to connect to my MS Access database, but for some reason it's not connecting. It's giving me an error, "data source name not found and no default driver specified". I already have connected with mysql with no problems. It's my first time trying to connect to MSAccess.

Here's my code:`

import java.sql.*;

import javax.swing.JOptionPane;


public class Database2 {

public String DBname = "comlab";
public static String host = "localhost";
public String Username = "";
public String Password = "";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

public Database2() {
}
public Connection conn;
public ResultSet rs = null;
public Statement st = null;
String dbconnect = "jdbc:";

public void connect() throws SQLException {
try {
if(conn==null){
this.conn = DriverManager.getConnection("jdbc:odbc:Database11");
this.st = this.conn.createStatement();}
else
this.st = this.conn.createStatement();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "The system could not connect to the database." + e, "Connection Error",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}

public void connect1() throws SQLException {
try {
this.conn = DriverManager.getConnection("jdbc:odbc:Database11");

} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "The system could not connect to the database." + e, "Connection Error",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}

public void close(Connection conn, Statement st, ResultSet rs) {
try {
if (rs != null)
this.rs.close();
if (st != null) {
}
if (conn != null)
this.conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public void close(Statement st, ResultSet rs) {
close(null, st, rs);
}

public void close(Statement st){
close(null, st, null);
}
}
`

Answer
import java.sql.*;

public class UserLogin {
    public static void main(String[] args) 
    {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\bank.accdb";

            Connection conn = DriverManager.getConnection(url, "username", "password");
            System.out.println("Connection Succesfull");
        }
        catch (Exception e) 
        {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
        }
    }
}
Comments