简体   繁体   English

如何在Java Swing中从MS Access数据库动态获取数据?

[英]How to fetch data dynamically in Java Swing from MS Access database?

I am working in Java swing and trying to fetch data from MS Access database dynamically. 我正在使用Java swing,并尝试从MS Access数据库动态获取数据。 Problem is it is only fetching first row but database contain four rows. 问题在于它仅获取第一行,而数据库包含四行。 I know the reason why it is fetching only first row again and again but after applying various logic I can't find a way to fetch second or further records. 我知道为什么一次又一次地仅提取第一行的原因,但是在应用各种逻辑后,我找不到一种方法来提取第二条记录或其他记录。 Please help. 请帮忙。

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

public class Ex_test extends JFrame 
{
    public static void main(String[] args) 
    {
        Ex_test ob=new Ex_test();
    }
    public Ex_test()
    {
    super("Array");
    int[] id=new int[15];
    String[] name=new String[15];
    int[] contact=new int[15];

    try
    {
        Connection con;
        Statement st;
        ResultSet rs;

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con=DriverManager.getConnection("jdbc:odbc:test");
        st=con.createStatement();
        rs=st.executeQuery("select * from test");
        while (rs.next())
        {
            for (int i=0;i<=3 ;i++ )
            {
                id[i]=rs.getInt("id");
                name[i]=rs.getString("sname");
                contact[i]=rs.getInt("contact");
                System.out.println(""+id[i]+name[i]+contact[i]);                
            }               
        }   
    }
    catch (Exception e)
    {

    }   
    setSize(1000,1000);
    setVisible(true);
    }   
}

rs.next() moves the cursor to the next item in the ResultSet or in other words, gets the next row in your ResultSet . rs.next()将光标移动到下一个项目中ResultSet或者换句话说,获取下一行的ResultSet Therefore, you should remove the for loop to get the next rows: 因此,您应该删除for循环以获取下一行:

while (rs.next()) {
    id[i]=rs.getInt("id");
    name[i]=rs.getString("sname");
    contact[i]=rs.getInt("contact");
    System.out.println(""+id[i]+name[i]+contact[i]);
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM