# ResultSet als Array an JTable übergeben



## endnic (28. Okt 2009)

Hallo alle miteinander...

ich habe mal wieder ein Problem... wo ich absolut nicht weiter komme...

Ich möchte gerne mein ResultSet in ein Array speichern und meiner JTable (in einer anderen Klasse) übergeben...
Soweit die Theorie! Habe auch schon die Forensuche genutzt und habe unter anderem folgendes gefunden:

ergebnisvektor-db-abfrage-jtable-anzeigen

daten-mysql-datenbankl-tabellen-gui-ausgeben

Leider verwirrt mich das noch mehr als es mir hilft! Ich weiß das diese Frage bestimmt schon x-mal gestellt wurde...aber vll kapiere ich es wenn einer von Euch mir das erklärt. 

Hier wird die Datenbank abgefragt (ResultSet lass ich noch über die Komandozeile ausgeben):

```
//get Searchresults from Database
		public void dbSearchTableTexts ()
		{
			try
			{
				Connection con = DriverManager.getConnection(sDatabaseURL, sDatabaseUser, sDatabasePass);
				PreparedStatement pstmt = con.prepareStatement("SELECT s.system_name, t.text_id, t.text_constant, t.text_en, " +
															   "t.text_de, t.create_date, u.shortcut, t.mod_date, " +
															   "ts.status_name FROM systems s, "+sUserSystem+"_texts t, "+sUserSystem+"_users u, texts_status ts  " +
															   "WHERE t.system_id = s.system_id AND u.user_id = t.user_id AND t.status_id = ts.status_id " +
															   "AND s.system_name LIKE ? AND " +
															   "t.text_id LIKE ? AND " +
															   "t.text_constant LIKE ? AND " +
															   "t.text_en LIKE ? AND " +
															   "t.text_de LIKE ? AND " +
															   "t.create_date LIKE ? AND " +
															   "u.shortcut LIKE ? AND " +
															   "t.mod_date LIKE ? AND " +
															   "ts.status_name LIKE ?" +
					   										   "ORDER BY t.text_id, t.status_id, t.mod_date ASC");
				pstmt.setString(1, "%" + sSystem + "%");
				pstmt.setString(2, "%" + sTextId + "%");
				pstmt.setString(3, "%" + sTextConstant + "%");
				pstmt.setString(4, "%" + sTextEn + "%");
				pstmt.setString(5, "%" + sTextDe + "%");
				pstmt.setString(6, "%" + dtCreateDate + "%");
				pstmt.setString(7, "%" + sShortCut + "%");
				pstmt.setString(8, "%" + dtModDate + "%");
				pstmt.setString(9, "%" + sStatus + "%");
				
				ResultSet rslt = pstmt.executeQuery();
				
				while (rslt.next())
				{	
					System.out.println(	rslt.getString(1) + "\t" +
										rslt.getString(2) + "\t" +
										rslt.getString(3) + "\t" +
										rslt.getString(4) + "\t" +
										rslt.getString(5) + "\t" +
										rslt.getString(6) + "\t" +
										rslt.getString(7) + "\t" +
										rslt.getString(8) + "\t" +
										rslt.getString(9));
					
				}
				pstmt.close();
			}
			catch (Exception e) 
			{
				System.out.println(e.getMessage());
			}
		}
```

in einer anderen Klasse steckt mein JTable drinnen:

```
//Create Scroll-Pane for Searchresults
	public JScrollPane getJspResults() 
	{
		if (jspResults == null) 
		{
			jspResults = new JScrollPane();
			jspResults.setBounds(new Rectangle(31, 132, 1080, 646));
		}
		return jspResults;
	}

	//Create table for search results
	public JTable getJtResults() 
	{
		if (jtResults == null) 
		{
			jtResults = new JTable();
			jtResults.setBounds(new Rectangle(32, 132, 1078, 644));
			
		}
		return jtResults;
	}
```

Meine Frage ist nun, wie ich die Results in mein JTable bekomme...

Kleine Anmerkung noch:
Meine MySQL - DB hat mehre Tabellen die je nach Auswahl des Nutzers in dem gleichen JTable angezeigt werden sollen (Natürlich nicht zeitgleich!).

@Mod: Falls dieses Thema doch unter "Datenbankprogrammierung" gehört, bitte verschieben. Danke


----------



## Verjigorm (28. Okt 2009)

Datenklasse erstellen, die genau die Werte aufnimmt, die deine Table braucht
Daten in Datenklasse schreiben und an Table übergeben.
Tabelle (bzw. Model) muss die Daten nur noch anzeigen


----------



## endnic (28. Okt 2009)

mmmmhhh....okay....
hört sich theoretisch einfach an...

kannst mir vll. noch ein praktisches Bsp. geben?


----------



## André Uhres (28. Okt 2009)

Aus den MetaData bekommen wir die Spaltenanzahl:

```
ResultSetMetaData md = rslt.getMetaData();
int columns = md.getColumnCount();
```

sowie die Spaltennamen:

```
Vector columnNames = new Vector();
for (int i = 1; i <= columns; i++){
    columnNames.addElement( md.getColumnName(i) );
}
```

Wir holen die Daten aus dem ResultSet:

```
Vector data = new Vector();
while (rslt.next()){
    Vector row = new Vector(columns);
    for (int i = 1; i <= columns; i++){
       row.addElement( rslt.getObject(i) );
    }
    data.addElement( row );
}
```

Diese Vektoren könnten wir jetzt schon an die JTable geben:

```
JTable table = new JTable(data, columnNames);
```

Eine Umwandlung in Arrays könnte so aussehen (möglicherweise unnötig):

```
Object[] colArray = columnNames.toArray();
Object[][] dataArray = new Object[data.size()][];
for (int row = 0; row < data.size(); row++) {
    Object[] rowArray = ((Vector) data.get(row)).toArray();
    dataArray[row] = rowArray;
}
```
Über die Kommunikation zwischen Klassen findest du sicher genug Stoff


----------



## endnic (28. Okt 2009)

Vielen Dank für deine ausführliche Antwort. 

Habe mir mal zum Üben 2 Testklassen geschrieben:

Klasse der DB-Abfrage:

```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;


public class Results 
{
	String 	sSystem = "def";
	String 	sTextId = "%";
	String 	sTextConstant = "%";
	String  sTextDe = "%";
	String  sTextEn = "%";
	String  dtCreateDate = "%";
	String 	sShortCut = "%";
	String  sStatus = "%";
	String  dtModDate = "%";
	String	sUserSystem = "def";
	

	String sDatabaseURL = "jdbc:mysql://*****/*****";
	String sDatabaseUser = "****";
	String sDatabasePass = "****";
	String sDbDriver = "com.mysql.jdbc.Driver";
	
	
	
	
	public static void main (String [] args)
	{
		new ShowTable().getJfTable().setVisible(true);
	}
	
	//get Searchresults from Database
	public void startSearch ()
	{	
		try 
		{
			Class.forName(sDbDriver);
		}
		catch (Exception e) 
		{
			System.out.println(e.getMessage());
		}
		
		try
		{
			Connection con = DriverManager.getConnection(sDatabaseURL, sDatabaseUser, sDatabasePass);
			PreparedStatement pstmt = con.prepareStatement("SELECT s.system_name, t.text_id, t.text_constant, t.text_en, " +
														   "t.text_de, t.create_date, u.shortcut, t.mod_date, " +
														   "ts.status_name FROM systems s, "+sUserSystem+"_texts t, "+sUserSystem+"_users u, texts_status ts  " +
														   "WHERE t.system_id = s.system_id AND u.user_id = t.user_id AND t.status_id = ts.status_id " +
														   "AND s.system_name LIKE ? AND " +
														   "t.text_id LIKE ? AND " +
														   "t.text_constant LIKE ? AND " +
														   "t.text_en LIKE ? AND " +
														   "t.text_de LIKE ? AND " +
														   "t.create_date LIKE ? AND " +
														   "u.shortcut LIKE ? AND " +
														   "t.mod_date LIKE ? AND " +
														   "ts.status_name LIKE ?" +
				   										   "ORDER BY t.text_id, t.status_id, t.mod_date ASC");
			pstmt.setString(1, "%" + sSystem + "%");
			pstmt.setString(2, "%" + sTextId + "%");
			pstmt.setString(3, "%" + sTextConstant + "%");
			pstmt.setString(4, "%" + sTextEn + "%");
			pstmt.setString(5, "%" + sTextDe + "%");
			pstmt.setString(6, "%" + dtCreateDate + "%");
			pstmt.setString(7, "%" + sShortCut + "%");
			pstmt.setString(8, "%" + dtModDate + "%");
			pstmt.setString(9, "%" + sStatus + "%");
			
			ResultSet rslt = pstmt.executeQuery();
			ResultSetMetaData md = rslt.getMetaData();
			int columns = md.getColumnCount();
			
			Vector columnNames = new Vector();
			for (int i = 1; i <= columns; i++)
			{
				columnNames.addElement(md.getColumnName(i));
			}
			
			Vector data = new Vector();
			while (rslt.next())
			{
				Vector row = new Vector(columns);
				for (int i = 1; i <= columns; i++)
				{
					row.addElement(rslt.getObject(i));
				}
				data.addElement(row);

			}
			new ShowTable().getJtResults(data, columnNames);
			
			pstmt.close();
		}
		catch (Exception e) 
		{
			System.out.println(e.getMessage());
		}
	}
}
```

Und eine mit der GUI:


```
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;
import javax.swing.JButton;
import java.awt.Rectangle;
import java.util.Vector;

import javax.swing.JScrollPane;
import javax.swing.JTable;

public class ShowTable 
{

	public JFrame jfTable = null;  //  @jve:decl-index=0:visual-constraint="415,18"
	public JPanel jcpTable = null;
	public JButton jbSearch = null;
	public JScrollPane jspResults = null;
	public JTable jtResults = null;

	public JFrame getJfTable() 
	{
		if (jfTable == null) 
		{
			jfTable = new JFrame();
			jfTable.setSize(new Dimension(489, 369));
			jfTable.setTitle("Test");
			jfTable.setContentPane(getJcpTable());
		}
		return jfTable;
	}

	public JPanel getJcpTable() 
	{
		if (jcpTable == null) 
		{
			jcpTable = new JPanel();
			jcpTable.setLayout(null);
			jcpTable.add(getJbSearch(), null);
			jcpTable.add(getJspResults(), null);
		}
		return jcpTable;
	}

	public JButton getJbSearch() 
	{
		if (jbSearch == null) 
		{
			jbSearch = new JButton();
			jbSearch.setBounds(new Rectangle(21, 22, 116, 28));
			jbSearch.setText("Search");
			jbSearch.addActionListener(new java.awt.event.ActionListener() 
			{
				public void actionPerformed(java.awt.event.ActionEvent e) 
				{
					new Results().startSearch();
				}
			});
		}
		return jbSearch;
	}

	public JScrollPane getJspResults() {
		if (jspResults == null) {
			jspResults = new JScrollPane();
			jspResults.setBounds(new Rectangle(15, 67, 452, 260));
			jspResults.setViewportView(getJtResults(null, null));
		}
		return jspResults;
	}

	public JTable getJtResults(Vector data, Vector columnNames) 
	{
		if (jtResults == null) 
		{
			jtResults = new JTable();

			System.out.println(data + "\n" + columnNames );
		}
		return jtResults;
	}
	
}
```

Übergeben wird alles richtig...aber leider zeigt er mir das Ergebnis noch nicht in meiner Tabelle...mir ist als hätte ich mal was von TableModel oder so gehört...wäre das der richtige Weg?


----------



## André Uhres (28. Okt 2009)

Wir sollten "Results" und "ShowTable" nicht bei jedem Search neu erzeugen, sondern wir setzen einfach ein neues TableModel:

```
import java.util.Vector;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Results {
...
    private final ShowTable showTable;
    public Results() {
        showTable = new ShowTable(this);
        showTable.getJfTable().setVisible(true);
    }
    public static void main(final String[] args) {
        Runnable gui = new Runnable() {
            @Override
            public void run() {
                new Results();
            }
        };
        //GUI must start on EventDispatchThread:
        SwingUtilities.invokeLater(gui);
    }
    //get Searchresults from Database
    public void startSearch() {
...
        showTable.getJtResults(null, null).setModel(new DefaultTableModel(data, columnNames));
...
    }
}
```


```
...
public class ShowTable {
...
    private final Results results;
    ShowTable(Results results) {
        this.results = results;
    }
...
    public JButton getJbSearch() {
        if (jbSearch == null) {
            jbSearch = new JButton();
            jbSearch.setBounds(new Rectangle(21, 22, 116, 28));
            jbSearch.setText("Search");
            jbSearch.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    results.startSearch();
                }
            });
        }
        return jbSearch;
    }
...
}
```


----------



## endnic (29. Okt 2009)

Hallo,

vielen Dank erstmal für Deine Mühe...

habe das mal mit meinen Testklassen ausprobiert...klappt hervorragend! :toll:

Nun dachte ich, was in den Testklassen klappt, muss auch in meinen richtigen Klassen klappen. aber denkste! Hab den ganzen Tag rumgebastelt und ausprobiert... nix zu machen! ;(

Hier mal alle wichtigen Klassen...

die Startklasse mit der main-Methode:

```
public class StartDbCare 
{
	public static void main(final String[] args) 
	{
        Runnable modulCare = new Runnable() 
        {
            @Override
            public void run() {
                new Login().getJfLogin().setVisible(true);
            }
        };
        //GUI must start on EventDispatchThread:
        SwingUtilities.invokeLater(modulCare);
    }
}
```

Meine GUI (der relevante Teil):
[JAVA=92]public final Search search;

	ModulCare(Search search)
	{
		this.search = search;
	}[/code]
[JAVA=268]//Create Scroll-Pane for Searchresults
	public JScrollPane getJspResults() 
	{
		if (jspResults == null) 
		{
			jspResults = new JScrollPane();
			jspResults.setBounds(new Rectangle(31, 132, 1080, 608));
			jspResults.setViewportView(getJtResults(null, null));
		}
		return jspResults;
	}

	//Create table for search results
	public JTable getJtResults(Vector vData, Vector vColumnNames ) 
	{
		if (jtResults == null) 
		{
			jtResults = new JTable();
			System.out.println("in der Tabelle auch angekommen" + "Daten: " + vData + "Namen: " + vColumnNames);
		}
		return jtResults;
	}[/code]
[JAVA=448]//Create search button
	public JButton getJbSearch() 
	{
		if (jbSearch == null) 
		{
			jbSearch = new JButton();
			jbSearch.setText("Search");
			jbSearch.setSize(new Dimension(120, 20));
			jbSearch.setLocation(new Point(988, 24));
			jbSearch.addActionListener(new java.awt.event.ActionListener() 
			{
				public void actionPerformed(java.awt.event.ActionEvent e) 
				{


					//set User-System-Id for right tables
					search.sUserSystem = sUserSystem;

					//set Parameters for table *_texts
					search.sSystem = jtfSystem.getText();
					search.sTextId = jtfTextId.getText();
					search.sTextConstant = jtfConstant.getText();
					search.sTextEn = jtfTextEn.getText();
					search.sTextDe = jtfTextDe.getText();
					search.dtCreateDate = jtfCreateDate.getText();
					search.sShortCut = jtfShortCut.getText();
					search.dtModDate = jtfModDate.getText();

					if (jcbStatus.getSelectedItem().equals("Active"))
					{
						search.sStatus = "act";
					}
					else if (jcbStatus.getSelectedItem().equals("History"))
					{
						search.sStatus = "his";
					}
					else if (jcbStatus.getSelectedItem().equals("Deleted"))
					{
						search.sStatus = "del";
					}
					else
					{
						search.sStatus = "%";
					}
					//set Parameter for table *_users
					search.sUserId = jtfUserId.getText();
					search.sFirstName = jtfFirstName.getText();
					search.sLastName = jtfLastName.getText();
					search.sUserShortCut = jtfUserShortCut.getText();
					search.sUserMail = jtfMail.getText();
					search.sUserLanguage = jtfUserLang.getText();
					search.sPermission = jtfPermission.getText();

					//load database driver
					search.dbDriverLoad();

					if (jcbSelectTable.getSelectedItem().equals(sUserSystem +"_texts"))
					{
						search.dbSearchTableTexts();
					}
					else if (jcbSelectTable.getSelectedItem().equals(sUserSystem +"_users"))
					{
						search.dbSearchTableUsers();
					}
					else if (jcbSelectTable.getSelectedItem().equals("languages"))
					{
						search.dbSearchTableLanguages();
					}
					else
					{
						search.dbSearchTableStatus();
					}
				}
			});
		}
		return jbSearch;
	}[/code]

Und die DB-Abfrage:

```
mport java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;


public class Search
{

	String	sUserId;
	String	sFirstName;
	String	sLastName;
	String  sUserShortCut;
	String  sUserMail;
	String	sUserLanguage;
	String	sPermission;
	String 	sSystem;
	String 	sTextId;
	String 	sTextConstant;
	String  sTextDe;
	String  sTextEn;
	String  dtCreateDate;
	String 	sShortCut;
	String  sStatus;
	String  dtModDate;
	String	sUserSystem;
	
	String sDatabaseURL = "jdbc:mysql://****/****";
	String sDatabaseUser = "****";
	String sDatabasePass = "****";
	String sDbDriver = "com.mysql.jdbc.Driver";
	
	public final ModulCare modulCare;
	
	public Search ()
	{
		modulCare = new ModulCare(this);
	}
	
	//load driver to connect to Database
	public void dbDriverLoad ()
	{
		try 
		{
			Class.forName(sDbDriver);
		}
		catch (Exception e) 
		{
			System.out.println(e.getMessage());
		}
	}
	
	public void connectToDb()
	{
		try 
		{
			Connection con = DriverManager.getConnection(sDatabaseURL, sDatabaseUser, sDatabasePass);
			con.close();
		} 
		catch (SQLException e) 
		{	
			e.printStackTrace();
		}
	}	
		//get Searchresults from Database
		public void dbSearchTableTexts ()
		{
			try
			{
				Connection con = DriverManager.getConnection(sDatabaseURL, sDatabaseUser, sDatabasePass);
				PreparedStatement pstmt = con.prepareStatement("SELECT s.system_name, t.text_id, t.text_constant, t.text_en, " +
															   "t.text_de, t.create_date, u.shortcut, t.mod_date, " +
															   "ts.status_name FROM systems s, "+sUserSystem+"_texts t, "+sUserSystem+"_users u, texts_status ts  " +
															   "WHERE t.system_id = s.system_id AND u.user_id = t.user_id AND t.status_id = ts.status_id " +
															   "AND s.system_name LIKE ? AND " +
															   "t.text_id LIKE ? AND " +
															   "t.text_constant LIKE ? AND " +
															   "t.text_en LIKE ? AND " +
															   "t.text_de LIKE ? AND " +
															   "t.create_date LIKE ? AND " +
															   "u.shortcut LIKE ? AND " +
															   "t.mod_date LIKE ? AND " +
															   "ts.status_name LIKE ?" +
					   										   "ORDER BY t.text_id, t.status_id, t.mod_date ASC");
				pstmt.setString(1, "%" + sSystem + "%");
				pstmt.setString(2, "%" + sTextId + "%");
				pstmt.setString(3, "%" + sTextConstant + "%");
				pstmt.setString(4, "%" + sTextEn + "%");
				pstmt.setString(5, "%" + sTextDe + "%");
				pstmt.setString(6, "%" + dtCreateDate + "%");
				pstmt.setString(7, "%" + sShortCut + "%");
				pstmt.setString(8, "%" + dtModDate + "%");
				pstmt.setString(9, "%" + sStatus + "%");
				
				ResultSet rslt = pstmt.executeQuery();
				ResultSetMetaData md = rslt.getMetaData();
				int iColumns = md.getColumnCount();
				
				Vector vColumnNames = new Vector();
				for (int i = 1; i <= iColumns; i++)
				{
					vColumnNames.addElement(md.getColumnName(i));
				}
				
				Vector vData = new Vector();
				while (rslt.next())
				{
					Vector vRow = new Vector(iColumns);
					for (int i = 1; i <= iColumns; i++)
					{
						vRow.addElement(rslt.getObject(i));
					}
					vData.addElement(vRow);

				}
				
				modulCare.getJtResults(null, null).setModel(new DefaultTableModel(vData, vColumnNames));
				System.out.println("in Search angekommen");
				
				pstmt.close();
			}
			catch (Exception e) 
			{
				System.out.println(e.getMessage());
			}
		}
}
```

Wenn ich das jetzt so auführe bekomm ich eine NullPointerException:

```
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at ModulCare$4.actionPerformed(ModulCare.java:464)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)
```


Ist ziemlich viel...aber vll. könntest Du nochmal gucken Andrè?


----------



## Michael... (29. Okt 2009)

endnic hat gesagt.:


> ```
> Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
> at ModulCare$4.actionPerformed(ModulCare.java:464)
> ```


Was steht den in der Zeile 464 von ModulCare???


----------



## endnic (29. Okt 2009)

sorry hat sich der Fehlerteufel eingeschlichen...

[JAVA=464]search.sUserSystem = sUserSystem;[/code]


----------



## Michael... (29. Okt 2009)

endnic hat gesagt.:


> sorry hat sich der Fehlerteufel eingeschlichen...
> [JAVA=464]search.sUserSystem = sUserSystem;[/code]


Würde sagen search ist null.
Neben bei bemerkt macht man Zuweisungen auf Membervariablen anderer Klassen in der objektorientierten Welt über setter-Methoden


----------

