简体   繁体   中英

JAVA : error on ExecuteUpdate

please i want to add an element to the database but i still have this error i don't know exactly where is the error and im sure about the sql query and my DB

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Ahmed,Saleh,2001/12/25,Cité les jasmins N°55, Sfax 3020,Saleh.BenAhmed@gmail.c' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2809)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1811)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1725)
    at utils.DBHelper.executeUpdate(DBHelper.java:78)
    at dao.EtudiantDAO.Ajout(EtudiantDAO.java:21)
    at dao.EtudiantDAO.main(EtudiantDAO.java:30)
Exception in thread "main" java.lang.NullPointerException
    at utils.DBHelper.closePreparedStatement(DBHelper.java:106)
    at utils.DBHelper.close(DBHelper.java:87)
    at dao.EtudiantDAO.Ajout(EtudiantDAO.java:22)
    at dao.EtudiantDAO.main(EtudiantDAO.java:30)

these are my classes : DBHelper.java

package utils;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;


public class DBHelper {
    public static Connection conn=null;
    static Statement stmt;
    private static PreparedStatement pstmt;
    private ResultSet rs;
    private static String driver_class_name="com.mysql.jdbc.Driver";
    private static String url="jdbc:mysql://localhost/gestetudiant";
    private static String username="root";
    private static String password="";

    public DBHelper(){


    }

    public static Connection getConnection(){



        try{
            Class.forName(driver_class_name);
            conn= DriverManager.getConnection(url, username, password);
        }
        catch(SQLException e){
            e.printStackTrace();
        }
        catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        return (Connection) conn;

    }


    public static PreparedStatement getPreparedStatement(String sql){
        try {
            pstmt= getConnection().prepareStatement(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return pstmt;
    }

    public static java.sql.Statement getStatement(){
        try {
            /* Création de l'objet gérant les requêtes */
            stmt = conn.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stmt;
    }

    public ResultSet executeQuery(String sql){
        try {
            rs=getStatement().executeQuery(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rs;
    }

    public static void executeUpdate(String sql){
        try {
            getStatement().executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }

    public static void close(){
        closeConnection();
        closePreparedStatement();
        closeStatement();

    }

    private static void closeStatement() {
        // TODO Auto-generated method stub
        try {
            stmt.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static void closePreparedStatement() {
        // TODO Auto-generated method stub
        try {
            pstmt.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static void closeConnection() {
        // TODO Auto-generated method stub
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Etudiant.java

package model;

import java.util.Date;

/**
 * @author jk
 *
 */
public class Etudiant {

    private String cin;
    private String nom;
    private String prenom;
    private String datenaissance;
    private String adresse;
    private String mail;
    private String tel;

    public Etudiant(String cin, String nom, String prenom, String string, String adresse, String mail,
            String tel) {
        super();
        this.cin = cin;
        this.nom = nom;
        this.prenom = prenom;
        this.datenaissance = string;
        this.adresse = adresse;
        this.mail = mail;
        this.tel = tel;
    }

    public Etudiant() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void finalize() throws Throwable   
    {
        super.finalize();  
    }

    public String getCin() {
        return cin;
    }

    public void setCin(String cin) {
        this.cin = cin;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public String getDatenaissance() {
        return datenaissance;
    }

    public void setDatenaissance(String datenaissance) {
        this.datenaissance = datenaissance;
    }

    public String getAdresse() {
        return adresse;
    }

    public void setAdresse(String adresse) {
        this.adresse = adresse;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }




}

EtudiantDAO.java

package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;


import model.Etudiant;
import utils.DBHelper;

public class EtudiantDAO {

    private static Connection conn;

    private static void Ajout(Etudiant pObjEtud)

    {
        conn=DBHelper.getConnection();
        DBHelper.executeUpdate("INSERT into etudiant(cin,nom,prenom,datenaissance,adresse,mail,tel) VALUES("+pObjEtud.getCin()+","+pObjEtud.getNom()+","+pObjEtud.getPrenom()+","+pObjEtud.getDatenaissance()+","+pObjEtud.getAdresse()+","+pObjEtud.getMail()+","+pObjEtud.getTel()+")");
        DBHelper.close();


    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Etudiant e=new Etudiant("0256341","Ben Ahmed","Saleh","2001/12/25","Cité les jasmins N°55, Sfax 3020","Saleh.BenAhmed@gmail.com","+216 55223344");
        Ajout(e);


    }



}

Text based fields need to be surrounded by quotes. Use the getPreparedStatement method of DBHelper

PreparedStatement ps = 
    DBHelper.getPreparedStatement("INSERT into etudiant(cin,nom,prenom,datenaissance,adresse,mail,tel) VALUES(?,?,?,?,?,?,?)");
ps.setString(1, pObjEtud.getCin());
...
ps.executeUpdate();

I think you have some missing ["] in the SQL query. I suggest using a PreparedStatement will help (And its a best practice anyway):

    String sql = "INSERT into etudiant"
            + "(cin,nom,prenom,datenaissance,adresse,mail,tel) VALUES"
            + "(?,?,?,?,?,?,?)";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, pObjEtud.getCin());
    ps.setString(2, pObjEtud.getNom());
    ps.setString(3, pObjEtud.getPrenom());
    //
    // continue all fields ...
    //
    ps.executeUpdate();

Kilani, if you are asking why it throws Exception, answer is basic.

In your main method you call for Ajout method which is basically calling executeUpdate and in executeUpdate after operation, it calls close operations.

But here you have only "update statement". You don't have PrepareStatement to close. pstmt variable never initialized but you try to close it.

Maybe you can check if pstmt null or not. That's it.

public static void executeUpdate(String sql){
    try {
        getStatement().executeUpdate(sql);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

public static void close(){
    closeConnection();
    closePreparedStatement();
    closeStatement();

}

...

private static void Ajout(Etudiant pObjEtud)

{
    conn=DBHelper.getConnection();
    DBHelper.executeUpdate("INSERT into etudiant(cin,nom,prenom,datenaissance,adresse,mail,tel) VALUES("+pObjEtud.getCin()+","+pObjEtud.getNom()+","+pObjEtud.getPrenom()+","+pObjEtud.getDatenaissance()+","+pObjEtud.getAdresse()+","+pObjEtud.getMail()+","+pObjEtud.getTel()+")");
    DBHelper.close();


}

These are your essential functions now where you got the problem.

1) in Ajout function, you call executeUpdate. Only psmt

2) After that you call close function. When you call executeUpdate you have initiated stmt variable. NOT pstmt. But when you call close() function you try to close both stmt and pstmt. Since stmt is not NULL, there is no problem with that. But pstmt is null.. Here it throws exception as NullPointer.

package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;


import model.Etudiant;
import utils.DBHelper;

public class EtudiantDAO {

    private static Connection conn;

    private static void Ajout(Etudiant pObjEtud)

    {
        conn=DBHelper.getConnection();      
        PreparedStatement ps = 
                DBHelper.getPreparedStatement("INSERT into etudiant(cin,nom,prenom,datenaissance,adresse,mail,tel) VALUES(?,?,?,?,?,?,?)");
        try{    
            ps.setString(1, pObjEtud.getCin());
            ps.setString(2, pObjEtud.getNom());
            ps.setString(3, pObjEtud.getPrenom());
            ps.setString(4, pObjEtud.getDatenaissance());
            ps.setString(5, pObjEtud.getAdresse());
            ps.setString(6, pObjEtud.getMail());
            ps.setString(7, pObjEtud.getTel());
            ps.executeUpdate();
             DBHelper.close();
        }
        catch(SQLException e){
                e.printStackTrace();
            }




    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Etudiant e=new Etudiant("14785214","Ben Ahmed","sami","2001/12/25","Cité les jasmins N°55, Sfax 3020","Saleh.BenAhmed@gmail.com","+216 55223344");
        Ajout(e);


    }



}

Problem Solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM