Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: ExecuteUpdate throws exception

  1. #1
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default ExecuteUpdate throws exception

    Hello,

    I am fairly new to java and thats the reason that I am following an online class to educate myself in this matter.

    For an assignement we have to built an applet containing buttos en jtextfields and jtextareas that will insert data in a MySql database.
    The connection to the database is correct.

    My code throws an exception on the following code "statement.executeUpdate(sset);"
    The function is called nieuwGerecht and resides in the Class Kreta.

    public void nieuwGerecht(){
    	try {
    		Statement statement = con.connection.createStatement();
    		System.out.println("Statement statement = con.connection.createStatement(); --> OK");
    		String sset;
    		sset = "INERT INTO 'afhaalmenus' ('naam_gerecht','prijs','ingredienten','recept')" +
    				"VALUES ('" + this.naam_gerecht + "', " + this.prijs + "', '" + this.ingredienten + "', '" + this.recept + "');";
    		System.out.println("built string --> OK");
    		statement.executeUpdate(sset);
    		System.out.println("statement.executeUpdate(sset); --> OK");
    		}
    	catch (Exception e){
    		System.out.println("foutje");
    	}
    	}

    The code where the button resides is in the Class KretaGUI.
    class bToevoegenListener implements ActionListener{
    		public void actionPerformed(ActionEvent event){
    			Kreta kreta = new Kreta();
    			kreta.setNaam_Gerecht(tNaam_gerecht.getText());
    			kreta.setPrijs(tPrijs.getText());
    			kreta.setNaam_Gerecht(tNaam_gerecht.getText());
    			kreta.setNaam_Gerecht(tNaam_gerecht.getText());
    			kreta.nieuwGerecht();
    		}
    	}

    What am I doing wrong?
    Also tips and commends on my programming are welcome.
    Thanks in advance

    PS: I attached the 3 classes containing all of the code as a .rar file --> Projectfiles.rar


  2. #2
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: ExecuteUpdate throws exception

    Hi, change this:
    catch (Exception e){
        System.out.println("foutje");
    }
    to
    catch (Exception e){
        e.printStackTrace();   
    }
    post the full stack trace.

  3. #3
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: ExecuteUpdate throws exception

    @PhHein:
    Do you mean this:

    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: 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 'INERT INTO 'afhaalmenus' ('naam_gerecht','prijs','ingredienten','recept')VA LUES ' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:40 9)
    at com.mysql.jdbc.Util.getInstance(Util.java:384)
    at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:3566)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:3498)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:19 59)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java :2113)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2562)
    at com.mysql.jdbc.StatementImpl.executeUpdate(Stateme ntImpl.java:1664)
    at com.mysql.jdbc.StatementImpl.executeUpdate(Stateme ntImpl.java:1583)
    at Kreta.nieuwGerecht(Kreta.java:129)
    at KretaGUI$bToevoegenListener.actionPerformed(KretaG UI.java:122)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown 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.mouseRe leased(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(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn 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.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  4. #4
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: ExecuteUpdate throws exception

    Yes. It tells you that your sql String (sset) is borked.

  5. #5
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: ExecuteUpdate throws exception

    My crosspost is also @ ExecuteUpdate throws exception

    --- Update ---

    Quote Originally Posted by PhHein View Post
    Yes. It tells you that your sql String (sset) is borked.
    Indeed..
    But I just don't see it:
    sset = "INSERT INTO 'afhaalmenus' ('menu_id','naam_gerecht','prijs','ingredienten','recept')" +
    				" VALUES ('"  + this.menu_id + "', '" + this.naam_gerecht + "', '" + this.prijs + "', '" + this.ingredienten + "', '" + this.recept + "');";

    I hope you can help me.

    Thanks for repleying.

  6. #6
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: ExecuteUpdate throws exception

    'afhaalmenus' ('menu_id','naam_gerecht','prijs','ingredienten',' recept') -> All these single quotes seem wrong to me.

  7. #7
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: ExecuteUpdate throws exception

    I found a solution that works:
    public void nieuwGerecht(){
    	try {
    		Statement statement = con.connection.createStatement();
     
    		String gget;
    		gget = "SELECT max(afhaalmenus.menu_id) FROM afhaalmenus;";
     
    		ResultSet rs = statement.executeQuery(gget);
    		rs.last();
    		this.menu_id = (rs.getInt(1)) + 1;
    		}
    	catch (Exception e) {
    		con.displaySQLErrors(e);		
    	}
     
    	try {
    		PreparedStatement sset = con.connection.prepareStatement("INSERT INTO afhaalmenus (menu_id,naam_gerecht,prijs,ingredienten,recept) VALUES (?,?,?,?,?)");
    		sset.setInt(1, this.menu_id);
    		sset.setString(2, this.naam_gerecht);
    		sset.setString(3, this.prijs);
    		sset.setString(4, this.ingredienten);
    		sset.setString(5, this.recept);
    		sset.executeUpdate();
    		}
    	catch (Exception e){
    		e.printStackTrace(); 
    	}
    	}

    Everybody thank you for helping!!!

  8. #8
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: ExecuteUpdate throws exception

    Hello,

    I finally completed my assignment and everything works fine. I've got 3 classes and I would love it if somebody could look through them and give me some tips and tricks concerning my code.
    NOTE: everything works and I completed the assignment but I just want to learn the "right" way and check if there aren't any stupid mistakes or redundancy in my code.

    Thanks in advance!!!ProjectFiles.zip

  9. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: ExecuteUpdate throws exception

    Congratulations!

    Most here won't follow links or download code. If you want your code evaluated, post it directly (copied and pasted) using code or highlight tags as you did in Post #7.

  10. #10
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: ExecuteUpdate throws exception

    @GregBrannon: Thanks!

    Here is my code for reviewing. I realy hope that you guys can give me some insightful tips or remarks.

    Connection Class
    //Importeer bibliotheken
    import java.io.FileInputStream;
    import java.sql.*;
    import java.util.Properties;
    import javax.swing.JOptionPane;
    // ****************************
     
    public class Connectie {
    	// Definieer private variabelen benodigd voor de connectie
    	private String host;
    	private String user;
    	private String password;
    	private String databasenaam;
     
    	Connection connection;
     
    	public void displaySQLErrors(Exception e) {
    		String error;
    		error = "SQL foutmelding: " + e.getMessage();
    		JOptionPane.showMessageDialog(null, error,"foutmelding",JOptionPane.ERROR_MESSAGE);
    	}
     
    	public Connectie() {
    		// Lees het config.ini bestand in
    		this.LeesIniBestand();
     
    		try {
    			Class.forName("com.mysql.jdbc.Driver").newInstance();
    			}
    		catch(Exception e) {
    			String error = "Niet mogelijk om de driver te laden";
    			JOptionPane.showMessageDialog(null, error,"foutmelding",JOptionPane.ERROR_MESSAGE);
     
    			System.exit(1);
    		}
    		try { // Bouw de connectiestring op
    			connection = DriverManager.getConnection("jdbc:mysql://" + this.host + "/" + 
    		this.databasenaam + "?user=" + this.user + "&password=" + this.password);
    			//String succes = "Er is een connectie met de database";
    			//JOptionPane.showMessageDialog(null, succes,"succes",JOptionPane.INFORMATION_MESSAGE);
    		}
    		catch(Exception e) {
    			displaySQLErrors(e);
    		}
    	}
     
    	public void LeesIniBestand() {
    		try{
    	      Properties p = new Properties();
    	      p.load(new FileInputStream("config.ini")); //Het bestand config.ini staat in de root map van java
    	      //Vul de database variabelen met de gegevens uit het .ini bestand
    	      this.host = p.getProperty("host");
    	      this.user = p.getProperty("user");
    	      this.password = p.getProperty("password");
    	      this.databasenaam = p.getProperty("databasenaam");
     
    	      //Schrijf variabelen naar scherm ter controle
    	      System.out.println("Host = " + p.getProperty("host"));
    	      System.out.println("user = " + p.getProperty("user"));
    	      System.out.println("Password = " + p.getProperty("password"));
    	      System.out.println("databasenaam = " + p.getProperty("databasenaam"));
    	      }
    	    catch (Exception e) {
    	      System.out.println(e);
    	      }
    	    }
    }

    GUI Class
    //Importeer bibliotheken
    import javax.swing.*;
     
    import java.util.Vector;
    //import java.awt.BorderLayout;
    import java.awt.*;
    //import javax.swing.JFrame;
    //import javax.swing.JList;
    //import javax.swing.JOptionPane;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    //import javax.swing.JPanel;
     
    //import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    // ************************************
     
    public class KretaGUI {
    	// In deze class wordt de GUI en alle events (JButton en JList) opgebouwd 
    	JFrame frame;
    	JButton bNieuw;
    	JButton bToevoegen;
    	JButton bBewerken;
    	JButton bWis;
    	JTextField tId;
    	JTextField tNaam_gerecht;
    	JTextField tPrijs;
    	JTextArea tRecept;
    	JTextArea tIngredienten;
    	JLabel lId;
    	JLabel lNaam_gerecht;
    	JLabel lPrijs;
    	JLabel lRecept;
    	JLabel lIngredienten;
    	JList gerechten;
     
    	public KretaGUI(){
    		Kreta kreta = new Kreta();
    		Vector tabel;
    		tabel = kreta.leesAlleGerechten();
     
    		frame = new JFrame("Afhaalmenus");
    		bNieuw = new JButton("Nieuw");
    		bNieuw.addActionListener(new bNieuwListener());
    		bToevoegen = new JButton("Toevoegen");
    		bToevoegen.addActionListener(new bToevoegenListener());
    		bBewerken = new JButton("Bewerken");
    		bBewerken.addActionListener(new bBewerkenListener());
    		bWis = new JButton("Wissen");
    		bWis.addActionListener(new bWisListener());
    		tId = new JTextField(3);
    		tId.setEditable(false); // Het veld ID mag niet handmatig worden aangepast
    		tNaam_gerecht = new JTextField(20);
    		tPrijs = new JTextField(20);
    		tRecept = new JTextArea(5,20);
    		tIngredienten = new JTextArea(5,20);
    		lId = new JLabel("Id:");
    		lNaam_gerecht = new JLabel("Naam:");
    		lPrijs = new JLabel("Prijs:");
    		lRecept = new JLabel("Recept:");
    		lIngredienten = new JLabel("Ingredienten:");
     
    		JPanel panelA = new JPanel(new FlowLayout(FlowLayout.LEFT)); //Plaats de buttons boven in het frame links uitgelijnd
    		JPanel panelB = new JPanel();  // Verzamel de textfields en textareas
    		JPanel panelC = new JPanel(); //JList
    		panelB.setLayout(new BoxLayout(panelB, BoxLayout.Y_AXIS)); //Plaats de labels en invoervelden onder elkaar
     
    		// opmaak JTextArea
    		JScrollPane sRecept = new JScrollPane(tRecept);
    		tRecept.setLineWrap(true);
    		sRecept.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    		sRecept.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
     
    		JScrollPane sIngredienten = new JScrollPane(tIngredienten);
    		tIngredienten.setLineWrap(true);
    		sIngredienten.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    		sIngredienten.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    		// ***************************
     
    		panelA.add(bNieuw);
    		panelA.add(bToevoegen);
    		panelA.add(bBewerken);
    		panelA.add(bWis);
    		panelB.add(lId);
    		panelB.add(tId);
    		panelB.add(lNaam_gerecht);
    		panelB.add(tNaam_gerecht);
    		panelB.add(lPrijs);
    		panelB.add(tPrijs);
    		panelB.add(lRecept);
    		panelB.add(sRecept);
    		panelB.add(lIngredienten);
    		panelB.add(sIngredienten);
     
    		gerechten = new JList(tabel);
    		gerechten.addListSelectionListener(new LijstListener());
    		gerechten.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Er kan maar 1 regel geselecteerd worden in de JList 
    		gerechten.setSelectedIndex(-1); // Geen regel is geselecteerd
    		panelC.add(gerechten);
     
    		frame.getContentPane().add(BorderLayout.NORTH,panelA);
    		frame.getContentPane().add(BorderLayout.WEST,panelB);
    		frame.getContentPane().add(BorderLayout.EAST,panelC);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(600,600);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
    	}
     
    	public static void main(String[] args) {
    		KretaGUI afhaal = new KretaGUI();
    	}
     
    	class bNieuwListener implements ActionListener{
    		// Maak alle velden leeg en verwijder de selectie van de JList als er op nieuw wordt geklikt.
    		public void actionPerformed(ActionEvent event){
    			gerechten.clearSelection(); // Zorg ervoor dat er geen recepten meer geselecteerd zijn 
    			tId.setText("");
    			tNaam_gerecht.setText("");
    			tPrijs.setText("");
    			tIngredienten.setText("");
    			tRecept.setText("");
    			tNaam_gerecht.requestFocus(); // Zet de focus in het veld naam
    		}
    	}
     
    	class bBewerkenListener implements ActionListener{
    		public void actionPerformed(ActionEvent event){
    			int Geselecteerd;
    			Geselecteerd = gerechten.getSelectedIndex(); // Bewaar de selectedindex van de JList
    			Kreta kreta = new Kreta();
    			kreta.setNaam_Gerecht(tNaam_gerecht.getText());
    			kreta.setPrijs(tPrijs.getText());
    			kreta.setIngredienten(tIngredienten.getText());
    			kreta.setRecept(tRecept.getText());
    			kreta.bewerkGerecht(Integer.parseInt(tId.getText()));
    			gerechten.setListData(kreta.leesAlleGerechten());
    			gerechten.repaint();
    			gerechten.setSelectedIndex(Geselecteerd); // Selecteer de rij in de JList van het huidige record
    		}
    	}
     
    	class bToevoegenListener implements ActionListener{
    		// Voeg het nieuwe gerecht toe aan de database (insert)
    		public void actionPerformed(ActionEvent event){
    			Kreta kreta = new Kreta();
    			kreta.setNaam_Gerecht(tNaam_gerecht.getText());
    			kreta.setPrijs(tPrijs.getText());
    			kreta.setIngredienten(tIngredienten.getText());
    			kreta.setRecept(tRecept.getText());
    			kreta.nieuwGerecht();
    			// Toon nieuwe menu_id in JTextfield tId
    			tId.setText(kreta.getId() + "");
    			// Vul de JList gerechten met de nieuwe data
    			gerechten.setListData(kreta.leesAlleGerechten());
    			gerechten.repaint();
    			// Indien het nieuwe record aan de tabel is toegevoegd dient de nieuwe regel in de JList geselecteerd te worden
    			int lastIndex = gerechten.getModel().getSize() - 1;
    			if (lastIndex >= 0) {
    				gerechten.setSelectedIndex(lastIndex);
    				}
    		}
    	}
     
    	// Deze Klasse roept wisRecept aan 
    	class bWisListener implements ActionListener{
    		public void actionPerformed(ActionEvent event){
    			Kreta kreta = new Kreta();
    			kreta.wisGerecht(Integer.parseInt(tId.getText()));
    			gerechten.setListData(kreta.leesAlleGerechten());
    			gerechten.repaint();
    			gerechten.clearSelection(); // Zorg ervoor dat er geen recepten meer geselecteerd zijn 
    			tId.setText("");
    			tNaam_gerecht.setText("");
    			tPrijs.setText("");
    			tIngredienten.setText("");
    			tRecept.setText("");
    			tNaam_gerecht.requestFocus(); // Zet de focus in het veld naam
    			;
    		}
    	}
     
    	class LijstListener implements ListSelectionListener
        {
            public void valueChanged(ListSelectionEvent e)
            {
                if (e.getValueIsAdjusting())
                {
                	Kreta kreta = new Kreta();
                    try
                    {
                        int menu_id = Integer.parseInt(((Vector)gerechten.getSelectedValue()).elementAt(0).toString());
                        kreta.leesGerecht(menu_id);
                        //tfdMenuID.setText(getmenu_id() + "");
                        tId.setText(kreta.getId() + "");
                        tNaam_gerecht.setText(kreta.getNaam_Gerecht());
                        tPrijs.setText(kreta.getPrijs());
                        tIngredienten.setText(kreta.getIngredienten());
                        tRecept.setText(kreta.getRecept());
                    }
                    catch(Exception ex)
                    {
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout", JOptionPane.ERROR_MESSAGE);
                    }
                }
             }
        }
    }

    Database Class
    //Importeer bibliotheken
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Vector;
    import java.sql.*;
    // *********************
     
    public class Kreta {
    	// In deze class worden de database bewerkingen uitgevoerd
    	private Connectie con;
    	private Vector vec;
    	private int menu_id;
    	private String naam_gerecht;
    	private String prijs;
    	private String ingredienten;
    	private String recept;
     
    	public void setId(int id){
    		this.menu_id=menu_id;
    	}
     
    	public int getId(){
    		return this.menu_id;
    	}
     
    	public void setNaam_Gerecht(String naam_gerecht){
    		this.naam_gerecht=naam_gerecht;
    	}
     
    	public String getNaam_Gerecht(){
    		return this.naam_gerecht;
    	}
     
    	public void setPrijs(String prijs){
    		this.prijs=prijs;
    	}
     
    	public String getPrijs(){
    		return this.prijs;
    	}
     
    	public void setIngredienten(String ingredienten){
    		this.ingredienten=ingredienten;
    	}
     
    	public String getIngredienten(){
    		return this.ingredienten;
    	}
     
    	public void setRecept(String recept){
    		this.recept=recept;
    	}
     
    	public String getRecept(){
    		return this.recept;
    	}
     
    	public Kreta(){
    		con = new Connectie();
    		vec = new Vector();
    	}
     
    	public Kreta(int menu_id,String naam_gerecht,String prijs,String ingredienten,String recept){
    		this();
    		this.menu_id = menu_id;
    		this.naam_gerecht = naam_gerecht;
    		this.prijs = prijs;
    		this.ingredienten = ingredienten;
    		this.recept = recept;
    	}
     
    	public Vector leesAlleGerechten(){
    		// Maak een vector die alle records uit de tabel afhaalmenus ophaalt.
    		try {
    			Statement statement = con.connection.createStatement();
    			String gget;
    			gget = "SELECT DISTINCT menu_id,naam_gerecht,prijs FROM afhaalmenus;";
     
    			ResultSet rs = statement.executeQuery(gget);
     
    			while (rs.next()){
    				Vector vRow = new Vector<>();
    				for(int x = 1;x <=3;x++){
    					vRow.addElement(rs.getString(x));
    				}
    				vec.add(vRow);
    			}
    		} catch (Exception e) {
    			con.displaySQLErrors(e);
    		}
    		return vec;
    	}
     
    public void leesGerecht(int id){
    	// Lees een record met het meegegeven id uit de tabel afhaalmenus
    		try{
    			PreparedStatement sset = con.connection.prepareStatement("SELECT DISTINCT * FROM afhaalmenus WHERE menu_id = ? ");
    			sset.setInt(1, id);			//Eerste parameter '?' is het menu_id welke wordt toegekend in het eerste stuk van de functie. 
     
    			ResultSet rs = sset.executeQuery();
    			rs.next();
    			this.menu_id = rs.getInt(1);
    			this.naam_gerecht = rs.getString(2);
    			this.prijs = rs.getString(3);
    			this.ingredienten = rs.getString(4);
    			this.recept = rs.getString(5);
    		}catch(Exception e){
    			e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception
    		}
    	}
     
    public void wisGerecht(int id){
    	// Delete het record met het menu_id id uit de tabel afhaalmenus
    	try {
    		PreparedStatement sset = con.connection.prepareStatement("DELETE FROM afhaalmenus WHERE menu_id = ?");
    		sset.setInt(1, id);			//Eerste parameter '?' is het menu_id welke wordt toegekend in het eerste stuk van de functie. 
    		sset.executeUpdate();
    		}
    	catch (Exception e){
    		e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception
    		}
    	}
     
    public void nieuwGerecht(){
    	try {
    		// Insert statement opbouwen
    		// Ik maak gebruik van een prepared statement omdat dit veel overzichtelijker werkt
    		// Met Statement.RETURN_GENERATED_KEYS krijg ik de nieuw aangemaakte menu_id terug
    		PreparedStatement sset = con.connection.prepareStatement("INSERT INTO afhaalmenus (naam_gerecht,prijs,ingredienten,recept) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
    		sset.setString(1, this.naam_gerecht);	//Eerste parameter '?' is het naam_gerecht
    		sset.setString(2, this.prijs);			//Tweede parameter '?' is het prijs
    		sset.setString(3, this.ingredienten);	//Derde parameter '?' is het ingredienten
    		sset.setString(4, this.recept);			//Vierde parameter '?' is het recept
    		sset.executeUpdate();
    		ResultSet tableKeys = sset.getGeneratedKeys();
    		tableKeys.next();
    		this.menu_id = tableKeys.getInt(1);
    		}
    	catch (Exception e){
    		e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception 
    		}
    	}
     
    public void bewerkGerecht(int id) {
    	// Update het geselecteerde record in de tabel afhaalmenus
        try
        {
        	PreparedStatement sset = con.connection.prepareStatement("UPDATE afhaalmenus SET naam_gerecht = ?,prijs = ?,ingredienten = ?,recept = ? " +
        			"WHERE menu_id = ?");
    		sset.setString(1, this.naam_gerecht);	
    		sset.setString(2, this.prijs);			
    		sset.setString(3, this.ingredienten);	
    		sset.setString(4, this.recept);	
    		sset.setInt(5, id);
    		sset.executeUpdate();
        }
        catch(Exception e) 	{
        e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception
        }
        }
     
    }

  11. #11
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: ExecuteUpdate throws exception

    These:
    private String naam_gerecht;
    private String prijs;
    private String ingredienten;
    private String recept;
    should be encasulated in a class Gerecht.
    Using Vector is very uncommon, I'd use a List.

  12. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: ExecuteUpdate throws exception

    The only thing that struck me is that the Swing application should be launched on the EDT:
        // a main method to launch the application on the EDT
        public static void main(String[] args)
        {
            SwingUtilities.invokeLater( new Runnable()
            {
                public void run()
                {
                    // KretaGUI afhaal = new KretaGUI();
                    // or simply:
                    new KretaGUI();
                }
            } );
        }

  13. #13
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: ExecuteUpdate throws exception

    I just recieved an email from my teacher.
    Because the assignement (i have to make an applet) sais that there hase to be a html file that calls the class.

    How should I go about this?

  14. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: ExecuteUpdate throws exception

    The Java Applets lesson includes a section on deployment that shows how to embed an Applet in a web page. Since recent Java versions are making this more and more difficult and complicated, if you're using an older version of Java (1.6 or earlier), I recommend finding a tutorial from a few years ago that will describe a simpler process.

Similar Threads

  1. [SOLVED] TableRowSorter throws Exception
    By Onur in forum AWT / Java Swing
    Replies: 1
    Last Post: November 7th, 2013, 06:23 AM
  2. executeUpdate Problem
    By moacirvidal in forum JDBC & Databases
    Replies: 4
    Last Post: May 22nd, 2012, 02:47 AM
  3. Singly Linked List of Integers, get(int i) function throws Null Pointer Exception
    By felixtum2010 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: June 23rd, 2011, 06:55 PM
  4. ZipInputStream Throws Illegalargument exception for diacritics
    By meghaladevi in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: October 12th, 2010, 02:32 AM
  5. [SOLVED] File.createTempFile() throws exception on Win7
    By jitinsingla in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: September 10th, 2010, 02:14 PM