java 用数据库值填充数组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5556518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
filling arraylist with database values
提问by CMP
/*
* 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);
}
}
}
this my full code my table model words fine fills up my table just fine but the array doesn't full and give me a stack trace :
这是我的完整代码,我的表格模型词很好地填满了我的表格,但数组没有填满并给我一个堆栈跟踪:
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
like this
像这样
采纳答案by Kerem Baydo?an
Comment out this line:
注释掉这一行:
//ArrayList senders = new ArrayList();
Change type to List and use generics
将类型更改为 List 并使用泛型
List<String> senders = new ArrayList<String>();
Add this lines: (DBUrl is your database address)
添加这一行:(DBUrl 是您的数据库地址)
Connection conn = null;
Statement stmt = null;
conn = DriverManager.getConnection("DBUrl");
stmt = con.createStatement();
Here is your modified code:
这是您修改后的代码:
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;
}
If you need more help just post stack trace of your exception.
如果您需要更多帮助,只需发布异常的堆栈跟踪即可。
Edit: Dont have your db drivers and enviroment on my local pc but following code should work.
编辑:我的本地电脑上没有你的数据库驱动程序和环境,但下面的代码应该可以工作。
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);
}
}
}
回答by Codemwnci
The only objects that can be null is the senders
object and stmt
object.
唯一可以为 null 的senders
对象是对象和stmt
对象。
A stack trace would determine which one is null.
堆栈跟踪将确定哪个为空。
From your full code listing, you can see in your constructor that you have a local and a global variable with the same name (stmt) this is bad practice, but is not the cause of your error.
从您的完整代码清单中,您可以在构造函数中看到您有一个具有相同名称 (stmt) 的局部变量和一个全局变量,这是不好的做法,但不是导致错误的原因。
Also, you are accessing the statement (stmt) in a static context, but only creating the statement in the constructor (which I cannot determine if it is ever executed). Your mixing of statics and non statics seems very confused.
此外,您正在静态上下文中访问语句 (stmt),但仅在构造函数中创建语句(我无法确定它是否被执行过)。您对静力学和非静力学的混合似乎很困惑。
So, the problem is almost certainly that the stmt object is null, and this is likely to be because you are accessing the getSend method statically, before the constructor is executed. A constructor should NOT be used to set up static variables. Some suggestions would be to
因此,问题几乎可以肯定是 stmt 对象为空,这很可能是因为您在执行构造函数之前静态访问 getSend 方法。构造函数不应用于设置静态变量。一些建议是
- look at the Singleton pattern
- look at static initialisers
- 看看单例模式
- 查看静态初始化程序
Both of these would solve your problem.
这两个都可以解决你的问题。