Domanda progetto in java

sara20

Utente Silver
6 Febbraio 2020
116
29
1
54
Buongiorno sto realizzando l'iscrizione con MVC in java swing e database sql (pgAdmin4) ma ho un problema tutto funziona ma nella tabella sql non mi vengono caricati i dati potete aiutarmi vi inserisco il codice relativo alla registrazione:
Java:
public class DaoUtente {
   
    public static boolean creaUtente(Utente utente) throws SQLException,Exception
    {
         String INSERIMENTO = "INSERT INTO utenti(nome, cognome, email, password, NumeroTelefonico, DataDiNascita) VALUES (?,?,?,?,?,?)";
        Connection conn = null;
        PreparedStatement stmt = null;
       
        if(effettua_accesso(utente.getEmail(),utente.getPassword()))  
        {
            conn = DBconnection.getInstance().getConn();
            stmt = conn.prepareStatement(INSERIMENTO);
            stmt.setString(1, utente.getNome());
            stmt.setString(2, utente.getCognome());
            stmt.setString(3, utente.getEmail());
            stmt.setString(4, utente.getPassword());
            stmt.setString(5, utente.getNumeroTelefonico());
            stmt.setString(6, utente.getDataDiNascita());
            stmt.executeUpdate();
            stmt.close();
            conn.close();
            return true;
        }
        return false;
           
    }
   
   
        public static boolean effettua_accesso(String Email, String password) throws SQLException,Exception
    {
         String RICERCA_PASSWORD="SELECT*FROM utenti where Email=? and password=?";
        Connection conn = DBconnection.getInstance().getConn();
        PreparedStatement stmt = conn.prepareStatement(RICERCA_PASSWORD);
        stmt.setString(1, Email);
        stmt.setString(2,password);
        ResultSet rs=stmt.executeQuery();
           
            if(!rs.next())
            {
                rs.close();
                return false;
            }
            else
            {
                rs.close();
                return true;
            }      
           
    }
Java:
public void creaUtente(Utente utente)
    {
        if(inputVuoto(utente)==false){
            {
                try {
                    if(DaoUtente.creaUtente(utente))
                    {
                        VisualizzazioneErrore("Iscrizione Effettuata con successo");
                    }
                    else
                    {
                        VisualizzazioneErrore("Utente già presente");
                    }
                } catch (SQLException e) {
                    VisualizzazioneErrore(e.getMessage()    );
                }
                catch(Exception e)
                {
                    VisualizzazioneErrore(e.getMessage());
                }
            }
        }
        else
        {
            VisualizzazioneErrore("alcuni campi sono vuoti");
        }
    }
SQL:
CREATE TABLE utenti
          (
           Id serial primary key
           Nome character varing(25),
           Cognome character varing(25),
           Email character varing(25),
           NumeroTelefonico character varing(25),
           DataDiNascita character varing(25),
           Password character varing(25)          
          );

Potete aiutami?
Grazie mille
 
public static boolean creaUtente(Utente utente) throws SQLException,Exception
{
String INSERIMENTO = "INSERT INTO utenti(nome, cognome, email, password, NumeroTelefonico, DataDiNascita) VALUES (?,?,?,?,?,?)";
Connection conn = null;
PreparedStatement stmt = null;

if(effettua_accesso(utente.getEmail(),utente.getPassword()))
{
conn = DBconnection.getInstance().getConn();
stmt = conn.prepareStatement(INSERIMENTO);
stmt.setString(1, utente.getNome());
stmt.setString(2, utente.getCognome());
stmt.setString(3, utente.getEmail());
stmt.setString(4, utente.getPassword());
stmt.setString(5, utente.getNumeroTelefonico());
stmt.setString(6, utente.getDataDiNascita());
stmt.executeUpdate();
stmt.close();
conn.close();
return true;
}
return false;

}
Ciao prova a catturare una possibile eccezione
Java:
try{

           conn = DBconnection.getInstance().getConn();
            stmt = conn.prepareStatement(INSERIMENTO);
            stmt.setString(1, utente.getNome());
            stmt.setString(2, utente.getCognome());
            stmt.setString(3, utente.getEmail());
            stmt.setString(4, utente.getPassword());
            stmt.setString(5, utente.getNumeroTelefonico());
            stmt.setString(6, utente.getDataDiNascita());
            stmt.executeUpdate();

}catch(SQLException e){
           e.printStackTrace(); //Stampa l'eccezione nell'esecuzione della query
}finally{
           if( conn != null){
                      try{
                                 conn.close();
                      }catch(SQLException e){
                                 e.printStackTrace(); //Stampa l'eccezione nella chiusura della connessione
                      }
           }
}

Potrebbero esserci errori di sintassi, non ricordo bene... comunque non so se avete fatto le eccezioni però praticamente sarebbero degli errori che se catturati (catch) si può sapere il tipo di errore, questa cattura avviene tramite del codice indicato nel try.
Finally invece server per scrivere del codice che verrà sicuramente lanciato a fine try-catch e nel caso delle chiamate sql spesso si ci mette la chiusura della connessione stessa.

Se non ci sono errori prova a stampare la query prima di eseguirla, per vedere se è settata bene.

Un altra cosa, prova a mettere tutto in minuscolo escluse le key-words sql(tipo INSERT, INTO, VALUES, ecc...) nella query, una volta riuscii a risolvere così.
 
Ultima modifica da un moderatore:
Ti consiglio di imparare jpa o hibernate
configurazione
Java:
src/main/java/META-INF/persistence.xml
//persistence.xml
<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
<persistence-unit name="persistenceUnitName" transaction-type="RESOURCE_LOCAL">
        <class>com.jpa.Student</class>
        <properties>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" /> <!-- DB Driver -->
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost/student" /> <!-- BD Mane -->
            <property name="hibernate.connection.user" value="postgres" /> <!-- DB User -->
            <property name="hibernate.connection.password" value="postgres" /> <!-- DB Password -->
 
            <property name="hibernate.hbm2ddl.auto" value="update" /> <!-- create / create-drop / update -->
//update database già creato aggiornamento

//create creazione tabelle al avvio se la tabella e esistente non la ricrea
/create-drop A ogni avvio ricrea la tabella         

            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="use_sql_comments" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

Classe di entità
INSERT INTO utenti(nome, cognome, email, password, NumeroTelefonico, DataDiNascita

@entity
@Table(name= " utenti_table")
public class Utente {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private  int idUtente;
private String nome;
private String cognome;
private String email;
private String password;

public Utente() {}
//getter
//setter
}


MAIN

EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnitName");

    EntityManager em = emf.createEntityManager();

    em.getTransaction().begin();

   Utente utente = new Utente();

   //set dati

    em.persist(utente); //persistenza

    em.getTransaction().commit();

 

    em.close();

    emf.close();




pom.xml



<project xmlns="http://maven.apache.org/POM/4.0.0"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

    http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.esempio</groupId>

    <artifactId>Example</artifactId>

    <packaging>jar</packaging>

    <version>1.0-SNAPSHOT</version>

    <name>Example</name>

    <url>http://maven.apache.org</url>

    <properties>

        <jdk.version>1.8</jdk.version>

    

    </properties>

    <dependencies>

<dependency>

</dependency>

<dependency>

<groupId>org.hibernate.javax.persistence</groupId>

<artifactId>hibernate-jpa-2.1-api</artifactId>

<version>1.0.2.Final</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.4.30.Final</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-entitymanager</artifactId>

<version>5.4.30.Final</version>

</dependency>

</dependencies>

    <build>

    <plugins>

    <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-assembly-plugin</artifactId>

            <version>2.2.1</version>

            <configuration>

                <descriptorRefs>

                    <descriptorRef>jar-with-dependencies</descriptorRef>

                </descriptorRefs>

                <archive>

                    <manifest>

                        <mainClass>com.Main</mainClass>

                    </manifest>

                </archive>

            </configuration>

        </plugin>

        <plugins>

        </build>

</project>



BUILD


mvn clean compile assembly:single
Messaggio unito automaticamente:

Ti consiglio di imparare jpa o hibernate
configurazione
src/main/java/META-INF/persistence.xml
//persistence.xml
<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnitName" transaction-type="RESOURCE_LOCAL">
<class>com.jpa.Student</class>
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" /> <!-- DB Driver -->
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/student" /> <!-- BD Mane -->
<property name="hibernate.connection.user" value="postgres" /> <!-- DB User -->
<property name="hibernate.connection.password" value="postgres" /> <!-- DB Password -->

<property name="hibernate.hbm2ddl.auto" value="update" /> <!-- create / create-drop / update -->
//update database già creato aggiornamento
//create creazione tabelle al avvio se la tabella e esistente non la ricrea
/create-drop A ogni avvio ricrea la tabella
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>

Classe di entità
INSERT INTO utenti(nome, cognome, email, password, NumeroTelefonico, DataDiNascita

@entity
@Table(name= " utenti_table")
public class Utente {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int idUtente;
private String nome;
private String cognome;
private String email;
private String password;

public Utente() {}
//getter
//setter
}


MAIN
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnitName");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Utente utente = new Utente();
//set dati
em.persist(utente); //persistenza
em.getTransaction().commit();

em.close();
emf.close();



pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.esempio</groupId>
<artifactId>Example</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Example</name>
<url>http://maven.apache.org</url>
<properties>
<jdk.version>1.8</jdk.version>

</properties>
<dependencies>
<dependency>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.30.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.30.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugins>
</build>
</project>


BUILD

mvn clean compile assembly:single
Scusa la linguaccia che uscita ma è la prima volta che scrivo sul forum :)
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/student" /> <!-- BD Mane -->
 
Ti consiglio di imparare jpa o hibernate
configurazione
src/main/java/META-INF/persistence.xml
//persistence.xml
<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnitName" transaction-type="RESOURCE_LOCAL">
<class>com.jpa.Student</class>
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" /> <!-- DB Driver -->
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/student" /> <!-- BD Mane -->
<property name="hibernate.connection.user" value="postgres" /> <!-- DB User -->
<property name="hibernate.connection.password" value="postgres" /> <!-- DB Password -->

<property name="hibernate.hbm2ddl.auto" value="update" /> <!-- create / create-drop / update -->
//update database già creato aggiornamento
//create creazione tabelle al avvio se la tabella e esistente non la ricrea
/create-drop A ogni avvio ricrea la tabella
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>

Classe di entità
INSERT INTO utenti(nome, cognome, email, password, NumeroTelefonico, DataDiNascita

@entity
@Table(name= " utenti_table")
public class Utente {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int idUtente;
private String nome;
private String cognome;
private String email;
private String password;

public Utente() {}
//getter
//setter
}


MAIN
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnitName");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Utente utente = new Utente();
//set dati
em.persist(utente); //persistenza
em.getTransaction().commit();

em.close();
emf.close();



pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.esempio</groupId>
<artifactId>Example</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Example</name>
<url>http://maven.apache.org</url>
<properties>
<jdk.version>1.8</jdk.version>

</properties>
<dependencies>
<dependency>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.30.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.30.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugins>
</build>
</project>


BUILD

mvn clean compile assembly:single
Messaggio unito automaticamente:


Scusa la linguaccia che uscita ma è la prima volta che scrivo sul forum :)
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/student" /> <!-- BD Mane -->
Ciao, ti conviene utilizzare la modalità di scrittura "codice". Per ora ho modificato io il tag, dalla prossima volta ti consiglio di usarla sin da subito, grazie :)