Torna indietro   Hardware Upgrade Forum > Software > Programmazione

HONOR Magic 8 Pro: ecco il primo TOP del 2026! La recensione
HONOR Magic 8 Pro: ecco il primo TOP del 2026! La recensione
HONOR ha finalmente lanciato il suo nuovo flagship: Magic 8 Pro. Lo abbiamo provato a fondo in queste settimane e ve lo raccontiamo nella nostra recensione completa. HONOR rimane fedele alle linee della versione precedente, aggiungendo però un nuovo tasto dedicato all'AI. Ma è al suo interno che c'è la vera rivoluzione grazie al nuovo Snapdragon 8 Elite Gen 5 e alla nuova MagicOS 10
Insta360 Link 2 Pro e 2C Pro: le webcam 4K che ti seguono, anche con gimbal integrata
Insta360 Link 2 Pro e 2C Pro: le webcam 4K che ti seguono, anche con gimbal integrata
Le webcam Insta360 Link 2 Pro e Link 2C Pro sono una proposta di fascia alta per chi cerca qualità 4K e tracciamento automatico del soggetto senza ricorrere a configurazioni complesse. Entrambi i modelli condividono sensore, ottiche e funzionalità audio avanzate, differenziandosi per il sistema di tracciamento: gimbal a due assi sul modello Link 2 Pro, soluzione digitale sul 2C Pro
Motorola edge 70: lo smartphone ultrasottile che non rinuncia a batteria e concretezza
Motorola edge 70: lo smartphone ultrasottile che non rinuncia a batteria e concretezza
Motorola edge 70 porta il concetto di smartphone ultrasottile su un terreno più concreto e accessibile: abbina uno spessore sotto i 6 mm a una batteria di capacità relativamente elevata, un display pOLED da 6,7 pollici e un comparto fotografico triplo da 50 MP. Non punta ai record di potenza, ma si configura come alternativa più pragmatica rispetto ai modelli sottili più costosi di Samsung e Apple
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 08-11-2008, 14:42   #1
UnknownSoldier
Member
 
Iscritto dal: Aug 2008
Messaggi: 210
[Java] SQLite e ResultSet non vanno d'accordo...

Salve, ho un problema. Sto creando un'applicazione standard per visualizzare i risultati di tabelle di database in una JTable. La mia applicazione dovrebbe poter connettersi a MySQL e SQLite. Con MySQL riesco a connettermi e ad eseguire query senza problemi. Con SQLite invece ho dei problemi.

Quando tento di eseguire una query con SQLite, viene lanciata una eccezione con il seguente messaggio: "ResultSet is TYPE_FORWARD ONLY". OK allora ho modificato lo statement in questo modo:

Codice PHP:
statement connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVEResultSet.CONCUR_READ_ONLY); 
Ma appena tento di connettermi ad SQLite un'eccezione viene lanciata con il seguente errore: "SQLite only supports TYPE_FORWARD_ONLY cursors".

Ma allora, come devo risolvere?

Se può esservi utile questa è la classe che gestisce la connessione al database che estende AbstractTableModel per i risultati visualizzabili nella JTable:

Codice PHP:
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class 
MyTableModel extends AbstractTableModel
{
    private 
Connection connection;
    private 
Statement statement;
    private 
ResultSet resultSet;
    private 
ResultSetMetaData metaData;
    private 
int numberOfRows 0;
    public 
boolean isConnected false;
    
    public 
void connect (String driverString databaseString usernameString passwordthrows Exception
    
{
        Class.
forName(driver);
        
        if (
driver.equals("com.mysql.jdbc.Driver"))
            
connection DriverManager.getConnection("jdbc:mysql://localhost/" databaseusernamepassword);
        else if (
driver.equals("org.sqlite.JDBC"))
            
connection DriverManager.getConnection("jdbc:sqlite:db.db");
        
        
statement connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVEResultSet.CONCUR_READ_ONLY);
        
        
isConnected true;
    }
    
    public 
void setQuery (String query)
    {
        try
        {
            if (
query.toLowerCase().contains("select"))
            {
                
resultSet statement.executeQuery (query);
                
                
metaData resultSet.getMetaData();
                
                
resultSet.last();
                
numberOfRows resultSet.getRow();
                
                
fireTableStructureChanged();
            }
            else
            {
                
statement.execute(query);
            }
        }
        catch (
Exception exception)
        {
            
JOptionPane.showMessageDialog(nullexception.getMessage(), "Errore"JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public Class 
getColumnClass (int column)
    {
        if (
resultSet != null)
        {
            try
            {
                
String className metaData.getColumnClassName(column 1);
                return Class.
forName(className);
            }
            catch (
Exception exception)
            {
                
exception.printStackTrace();
            }
        }
        
        return 
Object.class;
    }
    
    public 
int getColumnCount()
    {
        if (
resultSet != null)
        {
            try
            {
                return 
metaData.getColumnCount();
            }
            catch (
Exception exception)
            {
                
exception.printStackTrace();
            }
        }
        
        return 
0;
    }
    
    public 
String getColumnName (int column)
    {
        if (
resultSet != null)
        {
            try
            {
                return 
metaData.getColumnName (column 1);
            }
            catch (
Exception exception)
            {
                
exception.printStackTrace();
            }
        }
        
        return 
"";
    }
    
    public 
int getRowCount()
    {
        return 
numberOfRows;
    }
    
    public 
Object getValueAt (int rowint column)
    {
        if (
resultSet != null)
        {
            try
            {
                
resultSet.absolute(row 1);
                return 
resultSet.getObject(column 1);
            }
            catch (
Exception exception)
            {
                
exception.printStackTrace();
            }
        }
        
        return 
"";
    }

    public 
void disconnect()
    {
        try
        {
            
resultSet null;
            
fireTableStructureChanged();
            
            if (
connection != null)
                
connection.close();
            if (
statement != null)
                
statement.close();
            
            
isConnected false;
        }
        catch (
Exception exception)
        {
            
exception.printStackTrace();
        }
    }

UnknownSoldier è offline   Rispondi citando il messaggio o parte di esso
Old 08-11-2008, 23:55   #2
dierre
Senior Member
 
L'Avatar di dierre
 
Iscritto dal: Sep 2004
Città: Interamnia Urbs
Messaggi: 2126
Ho trovato questo se ti può essere utile:

SQLite only supports forward cursors,
that is, when you make a SELECT statement and receive a set of rows,
you can only work through those rows one by one from the top using
next(). This is not a limitation, as this combined with the expressive
power of SQL lets you move around in a database in any desirable
fashion.
__________________
Un wormhole (buco di tarlo, in italiano), detto anche Ponte di Einstein-Rosen, è una ipotetica caratteristica topologica dello spaziotempo che è essenzialmente una "scorciatoia" da un punto dell'universo a un altro, che permetterebbe di viaggiare tra di essi più velocemente di quanto impiegherebbe la luce a percorrere la distanza attraverso lo spazio normale.
Go to a Wormhole
dierre è offline   Rispondi citando il messaggio o parte di esso
Old 09-11-2008, 09:04   #3
UnknownSoldier
Member
 
Iscritto dal: Aug 2008
Messaggi: 210
Quote:
Originariamente inviato da dierre Guarda i messaggi
Ho trovato questo se ti può essere utile:

SQLite only supports forward cursors,
that is, when you make a SELECT statement and receive a set of rows,
you can only work through those rows one by one from the top using
next(). This is not a limitation, as this combined with the expressive
power of SQL lets you move around in a database in any desirable
fashion.
Sì grazie infatti ho capito che quindi non posso utilizzare i metodi last e absolute di ResultSet. Ho pensato quindi di salvare tutti i valori in un ArrayList < ArrayList < String > >

Ora però provo e spero che non ci siano problemi...
UnknownSoldier è offline   Rispondi citando il messaggio o parte di esso
Old 09-11-2008, 10:47   #4
UnknownSoldier
Member
 
Iscritto dal: Aug 2008
Messaggi: 210
Allora, ho capito che la soluzione fosse quella di evitare di utilizzare i metodi last e absolute di ResultSet, allora con un ciclo while ho letto tutte le righe in modo sequenziale e ho salvato tutto in ArrayList < ArrayList < Object > >. Però ogni volta che eseguo una SELECT query viene lanciata una IllegalStateException:

Codice PHP:
java.lang.IllegalStateExceptionSQLite JDBCinconsistent internal state
    at org
.sqlite.RS.checkCol(RS.java:62)
    
at org.sqlite.RS.getColumnCount(RS.java:315)
    
at MyTableModel.getColumnCount(MyTableModel.java:81)
    
at javax.swing.JTable.createDefaultColumnsFromModel(JTable.java:1205)
    
at javax.swing.JTable.tableChanged(JTable.java:4324)
    
at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
    
at javax.swing.table.AbstractTableModel.fireTableStructureChanged(AbstractTableModel.java:200)
    
at MyTableModel.setQuery(MyTableModel.java:61)
    
at DFDatabase$QueryHandler.actionPerformed(DFDatabase.java:67)
    
at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
    
at javax.swing.JTextField.postActionEvent(JTextField.java:705)
    
at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
    
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    
at javax.swing.JComponent.processKeyBinding(JComponent.java:2849)
    
at javax.swing.JComponent.processKeyBindings(JComponent.java:2884)
    
at javax.swing.JComponent.processKeyEvent(JComponent.java:2812)
    
at java.awt.Component.processEvent(Component.java:5818)
    
at java.awt.Container.processEvent(Container.java:2058)
    
at java.awt.Component.dispatchEventImpl(Component.java:4413)
    
at java.awt.Container.dispatchEventImpl(Container.java:2116)
    
at java.awt.Component.dispatchEvent(Component.java:4243)
    
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:697)
    
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:962)
    
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:834)
    
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:661)
    
at java.awt.Component.dispatchEventImpl(Component.java:4285)
    
at java.awt.Container.dispatchEventImpl(Container.java:2116)
    
at java.awt.Window.dispatchEventImpl(Window.java:2440)
    
at java.awt.Component.dispatchEvent(Component.java:4243)
    
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121
Questo è MyTableModel che ho modificato:
Codice PHP:
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;

public class 
MyTableModel extends AbstractTableModel
{
    private 
Connection connection;
    private 
Statement statement;
    private 
ResultSet resultSet;
    private 
ResultSetMetaData metaData;
    private 
int numberOfRows;
    private 
ArrayList ArrayList Object > > tableList = new ArrayList ArrayList Object > >();
    private 
ArrayList Object rows = new ArrayList Object >();
    public 
boolean isConnected false;
    
    public 
void connect (String driverString databaseString usernameString passwordthrows Exception
    
{
        Class.
forName(driver);
        
        if (
driver.equals("com.mysql.jdbc.Driver"))
            
connection DriverManager.getConnection("jdbc:mysql://localhost/" databaseusernamepassword);
        else if (
driver.equals("org.sqlite.JDBC"))
            
connection DriverManager.getConnection("jdbc:sqlite:db.db");
        
        
statement connection.createStatement();
        
        
numberOfRows 0;
        
isConnected true;
    }
    
    public 
void setQuery (String query)
    {
        try
        {
            if (
query.toLowerCase().contains("select"))
            {
                
resultSet statement.executeQuery (query);
                
metaData resultSet.getMetaData();
                
                
tableList.clear();
                
                for (
int i 1<= metaData.getColumnCount(); i++)
                    
rows.add (resultSet.getObject (i));
                
                while (
resultSet.next())
                {
                    for (
int i 1<= metaData.getColumnCount(); i++)
                        
rows.add (resultSet.getObject (i));
                    
                    
tableList.add (rows);
                    
rows.clear();
                }
                
                
numberOfRows tableList.size();
                
                
fireTableStructureChanged(); //riga 61
            
}
            else
            {
                
statement.execute(query);
                
JOptionPane.showMessageDialog(null"Query eseguita con successo""Query OK"JOptionPane.INFORMATION_MESSAGE);
            }
        }
        catch (
Exception exception)
        {
            
JOptionPane.showMessageDialog(nullexception.getMessage(), "Errore"JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public 
int getColumnCount()
    {
        if (
resultSet != null)
        {
            try
            {
                return 
metaData.getColumnCount(); //riga 81
            
}
            catch (
Exception exception)
            {
                
exception.printStackTrace();
            }
        }
        
        return 
0;
    }
    
    public 
String getColumnName (int column)
    {
        if (
resultSet != null)
        {
            try
            {
                return 
metaData.getColumnName (column 1);
            }
            catch (
Exception exception)
            {
                
exception.printStackTrace();
            }
        }
        
        return 
"";
    }
    
    public 
int getRowCount()
    {
        return 
numberOfRows;
    }
    
    public 
Object getValueAt (int rowint column)
    {
        if (
resultSet != null)
        {
            
ArrayList Object rowList tableList.get(row);
            return 
rowList.get(column);
        }
        
        return 
"";
    }

    public 
void disconnect()
    {
        try
        {
            
resultSet null;
            
tableList.clear();
            
fireTableStructureChanged();
            
            if (
connection != null)
                
connection.close();
            if (
statement != null)
                
statement.close();
            
            
isConnected false;
        }
        catch (
Exception exception)
        {
            
exception.printStackTrace();
        }
    }

UnknownSoldier è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


HONOR Magic 8 Pro: ecco il primo TOP del 2026! La recensione HONOR Magic 8 Pro: ecco il primo TOP del 2026! L...
Insta360 Link 2 Pro e 2C Pro: le webcam 4K che ti seguono, anche con gimbal integrata Insta360 Link 2 Pro e 2C Pro: le webcam 4K che t...
Motorola edge 70: lo smartphone ultrasottile che non rinuncia a batteria e concretezza Motorola edge 70: lo smartphone ultrasottile che...
Display, mini PC, periferiche e networking: le novità ASUS al CES 2026 Display, mini PC, periferiche e networking: le n...
Le novità ASUS per il 2026 nel settore dei PC desktop Le novità ASUS per il 2026 nel settore de...
The Sims entra in una nuova era, ma l'ac...
Netflix, Disney o Prime Video: qual &egr...
Perplexity blocca la generazione di imma...
Iliad rilancia Giga 200 e Giga 250 al po...
Apre un nuovo hub di ricarica Electra pr...
Windows 11, il primo aggiornamento del 2...
L'odiata interfaccia utente di Windows 8...
Apple, Xiaomi, Motorola, Google e vivo: ...
Robot aspirapolvere a metà prezzo: Amazo...
L'AI distruggerà milioni di posti di lav...
Gli obbligazionisti di Oracle intentano ...
Amazon scatenata: robot aspirapolvere, s...
007 First Light, requisiti sbagliati: IO...
Il secondo leasing sociale francese ragg...
Anche Chrome diventerà un browser...
Chromium
GPU-Z
OCCT
LibreOffice Portable
Opera One Portable
Opera One 106
CCleaner Portable
CCleaner Standard
Cpu-Z
Driver NVIDIA GeForce 546.65 WHQL
SmartFTP
Trillian
Google Chrome Portable
Google Chrome 120
VirtualBox
Tutti gli articoli Tutte le news Tutti i download

Strumenti

Regole
Non Puoi aprire nuove discussioni
Non Puoi rispondere ai messaggi
Non Puoi allegare file
Non Puoi modificare i tuoi messaggi

Il codice vB è On
Le Faccine sono On
Il codice [IMG] è On
Il codice HTML è Off
Vai al Forum


Tutti gli orari sono GMT +1. Ora sono le: 16:54.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Served by www3v