-1

I try to create a connection between JDBC and MS Access.

I follow the instruction as per this link. I am using IntelliJ Idea. Here I am sharing some snaps to describe my problem.

enter image description here

This is the code that I write down to make a connection with Database Database2. But as you can see there is no error neither any output. Now I am sharing the table structure and content on the table.

enter image description here

2nd picture is enter image description here

My code is:

import java.sql.*;

public class Connection_sample {
public static void main(String[] args) {
    try {
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        Connection conn= DriverManager.getConnection("jdbc:ucanaccess://D://tutorial/Database2.accdb");
        Statement s = conn.createStatement();
        s.executeQuery("select * from Student");
        ResultSet rset = s.getResultSet();

        while (rset.next()) {
            System.out.println(rset.getInt(1)+""+rset.getInt(2));
        }
    } catch (SQLException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}
}

Can anyone help me to find the error?

Encipher
  • 1,037
  • 8
  • 22
  • Please don't post images of code, but post code as text. Possibly your problem is the result of using `getResultSet()` instead of using the result set returned by `executeQuery()`. You should only use `getResultSet()` in combination with `execute()`. – Mark Rotteveel Nov 06 '19 at 18:18
  • I change it like this `ResultSet rset= s.executeQuery("select * from Student"); ` and it is working. Thanks a lot. Could you please explain, why this type of change neede? – Encipher Nov 06 '19 at 18:54

1 Answers1

1

Your problem is the result of using getResultSet() instead of using the result set returned by executeQuery(). You should only use getResultSet() in combination with execute().

A result set should only be obtained once, and it was already returned from executeQuery (which you ignored). When you called getResultSet, you - apparently - got an empty one (which technically violates the contract).

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158