用数据库值填充arraylist

时间:2011-04-05 18:18:50

标签: java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package XawalaManager;

import java.sql.*; // DB handling package
import java.util.*;
import javax.swing.table.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.TableModelEvent;

/**
 *
 * @author Abdi Aden
 */
public class DBHandler extends AbstractTableModel {


    private static Connection connection;

    private static Statement stmt;
    Vector columnHeaders;
    Vector tableData;
    static int id;
   public static int autokey = -1;
    static String [] contactList;
    static  ArrayList senders =  new ArrayList();

    public DBHandler() {
        Vector rowData;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            // Assumes Messages.mdb is in the same folder as MessageData.class
            String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=olympic.mdb;";
            connection = DriverManager.getConnection(sourceURL, "admin", "");
            stmt = connection.createStatement();           
            String sql = "Select * FROM senderTable";
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();

            int count = md.getColumnCount();
            columnHeaders = new Vector(count);
           tableData = new Vector();
            for (int i = 1; i <= count; i++) {
                columnHeaders.addElement(md.getColumnName(i));
            }
            while (rs.next()) {
                rowData = new Vector(count);
                for (int i = 1; i <= count; i++) {
                    rowData.addElement(rs.getObject(i));
                }
               tableData.addElement(rowData);
            }


        } catch (Exception e) {
            System.out.println("There is an connection error:  " +e );
        }
    }

    public int getColumnCount() {
        return columnHeaders.size();
    }

    public int getRowCount() {
        return tableData.size();
    }

    public Object getValueAt(int row, int column) {
        Vector rowData = (Vector) (tableData.elementAt(row));
        return rowData.elementAt(column);
    }



    public boolean isCellEditable(int row, int column) {
        return false;
    }

    public String getColumnName(int column) {
        return (String) (columnHeaders.elementAt(column));
    }






    public static ArrayList getSend(){

        try{
            ResultSet res = stmt.executeQuery("SELECT * FROM senderTable");
            //ArrayList senders =  new ArrayList();
            while (res.next()){
                String send = res.getString(2);
                senders.add(send);

            }
        }catch (Exception e ){
            System.out.println("getSend "+e);
            return null;
        }
        return senders;
    }

    // close the database

    public static void close() {
        try {
            connection.close();
        } catch (Exception e) {
            // this shouldn't happen
            System.out.println("close"+e);
        }
    }
}

这是我的完整代码,我的表模型字很好地填满了我的表,但阵列没有满,给我一个堆栈跟踪:

getSend java.lang.NullPointerException
Exception in thread "main" java.lang.NullPointerException
        at XawalaManager.mainView.<init>(mainView.java:86)
        at XawalaManager.XawalaManager.<init>(XawalaManager.java:40)
        at XawalaManager.XawalaManager.main(XawalaManager.java:108)
Java Result: 1
像这样

2 个答案:

答案 0 :(得分:1)

注释掉这一行:

//ArrayList senders =  new ArrayList();

将类型更改为列表并使用泛型

List<String> senders =  new ArrayList<String>();

添加以下行:( DBUrl是您的数据库地址)

Connection conn = null;
Statement  stmt = null;
conn = DriverManager.getConnection("DBUrl");
stmt = con.createStatement();

以下是您修改后的代码:

public static ArrayList getSend(){

  Connection conn = null;
  Statement  stmt = null;
  ResultSet res = null;
  List<String> senders =  new ArrayList<String>();

  try{
    conn = DriverManager.getConnection("DBUrl");
    stmt = con.createStatement();
    res = stmt.executeQuery("SELECT * FROM senderTable");

    while (res.next()){
        String send = res.getString(2);
        senders.add(send);

    }
  }catch (Exception e ){
    System.out.println("getSend "+e);
    return null;
  }
 return senders;
}

如果您需要更多帮助,只需发布​​异常的堆栈跟踪。

编辑:我的本地电脑上没有你的数据库驱动程序和环境,但下面的代码应该有用。

import java.sql.*;
import java.util.*;
import javax.swing.table.AbstractTableModel;

public class DBHandler extends AbstractTableModel {

    private static Connection connection;
    private static Statement stmt;
    List<String> columnHeaders;
    List<List<String>> tableData;
    static int id;
    public static int autokey = -1;
    static String[] contactList;
    static ArrayList<String> senders = new ArrayList<String>();

    public DBHandler() {
        List rowData = null;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=olympic.mdb;";
            connection = DriverManager.getConnection(sourceURL, "admin", "");
            stmt = connection.createStatement();
            String sql = "Select * FROM senderTable";
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();

            int count = md.getColumnCount();
            columnHeaders = new ArrayList<String>();
            tableData = new ArrayList<List<String>>();
            for (int i = 1; i <= count; i++) {
                columnHeaders.add(md.getColumnName(i));
            }
            while (rs.next()) {
                rowData = new ArrayList<String>();
                for (int i = 1; i <= count; i++) {
                    rowData.add(rs.getObject(i));
                }
                tableData.add(rowData);
            }


        } catch (Exception e) {
            System.out.println("There is an connection error:  " + e);
        }
    }

    public int getColumnCount() {
        return columnHeaders.size();
    }

    public int getRowCount() {
        return tableData.size();
    }

    public Object getValueAt(int row, int column) {
        ArrayList rowData = (ArrayList) (tableData.get(row));
        return rowData.get(column);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }

    @Override
    public String getColumnName(int column) {
        return (String) (columnHeaders.get(column));
    }

    public static ArrayList getSend() {

        try {
            ResultSet res = stmt.executeQuery("SELECT * FROM senderTable");
            while (res.next()) {
                String send = res.getString(2);
                senders.add(send);
            }
        } catch (Exception e) {
            System.out.println("getSend " + e);
            return null;
        }
        return senders;
    }

    public static void close() {
        try {
            connection.close();
        } catch (Exception e) {
            System.out.println("close" + e);
        }
    }
}

答案 1 :(得分:0)

唯一可以为null的对象是senders对象和stmt对象。

堆栈跟踪将确定哪一个为空。

从完整的代码清单中,您可以在构造函数中看到您有一个具有相同名称的本地变量和全局变量(stmt)这是不好的做法,但不是导致错误的原因。

此外,您正在静态上下文中访问语句(stmt),但只在构造函数中创建语句(我无法确定它是否曾被执行过)。你对静力学和非静力学的混合似乎很困惑。

因此,问题几乎可以肯定是stmt对象为null,这很可能是因为在执行构造函数之前静态访问getSend方法。不应使用构造函数来设置静态变量。

是一些建议
  • 查看Singleton模式
  • 查看静态初始化程序

这两个都可以解决您的问题。