I am trying to pass an object as parameter to another class wich contains a SQL connection:
Base class is a swing class where this method is the essential to know for my question:

public void actionPerformed(ActionEvent e)
            {
            	ModelNY mo = new ModelNY();	
            	mo.setPersonID(txtField1.getText());
            	mo.setFName(txtField2.getText());
            	mo.setLName(txtField3.getText());
            	mo.setAdress(txtField4.getText());
            	mo.setEmail(txtField5.getText());
            	
            	ConnectToMySQL c = new ConnectToMySQL();
            	c.connect(mo);

My SQL class recieves this object and I want to get each value an put it inot the 'todo' string:

public void connect(Object o) {
		  Connection conn = null;
		  try {
   
		      Class.forName("com.mysql.jdbc.Driver").newInstance();
		      conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "Mg78QnuE");
		  
String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost) "+
		        	  "values ('"+text1+"', '"+text2+"', '"+text3+"', '"+text4+"', '"+text5+"')") ;
			  
		      Statement statement = conn.createStatement();
	          statement.executeUpdate(todo);

I want to say something like o.getidpersoner() where I say

"values ('"+text1+"'

as a replacement for text1 you could say.


But I cant say that. I've trid saying o.getClass so that works fine.

Anybody that can help me?

Okay? So do it. You have to make sure that that method exists in the class though, of course.

P.S. Do Not cobble together statements unless you want sporadic SQL syntax errors and (un)intentional SQL injection attacks. See the JDBC Tutorials for PreparedStatement (and don't say you have, because you haven't or you wouldn't be doing that).

Thank You, I will look into that...

Any reason to receive generic Object instead of receiving ModelNY? Also why not using PreparedStatement as showed bellow?

public void connect(ModelNY modelNY) {
		  Connection conn = null;
		  try {
   
		      Class.forName("com.mysql.jdbc.Driver").newInstance();
		      conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "Mg78QnuE");
		  
String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost) "+
		        	  "values (?,?,?,?,?)") ;
			  
		      PreparedStatement statement = conn.createStatement();
		      statement.setString(1, modelNY.getPersonID());
		      statement.setString(2, modelNY.getFName());
		      statement.setString(3, modelNY.getLName());
		      statement.setString(4, modelNY.getAdress());
		      statement.setString(5, modelNY.getEmail());
	          statement.executeUpdate(todo);

Hmmm, please nothing to your topics

1/ maybe open connection on App startUp, close that on App Exit, to avoid long task during ActionPerformed (from JButton???), in your case GUI probably freeze for second and more ...
2/ there nothing about Object (mo), if is TableModel, TreeModel then you can directly (in Sql statement block) upload value into Vector or another arry (depends of your Model),
3/ if your model contains more than one row then you have to iterate or loop throught model rows (depends of model and JComponents)
4/ search for PreparedStatement
5/ in this case isn't necessary past probably huge Object between plain voids
6/ whats your question exactly, because there is (maybe) lost of problems with basic definitions for Array, JComponents, AbstractClass and your problem is concerning with SQL systax & JDBC, not about passing any Object

Hi, I tried your example but I get the error:

Type Mismatch: Cannot convert from statement to PreparedStatement.

Casting wont work:
com.mysql.jdbc.StatementImpl cannot be cast to com.mysql.jdbc.PreparedStatement

Because peter made a mistake. You use prepareStatement not createStatement (then again, maybe he did it on purpose to see if you even bothered to look at the docs you've been pointed to).

You could ask him what his intention was ;-)
The JDBC Tutorials for PreparedStatement. Do you have a link to it?
Thank You!

here

go to JDBC, then to PreparedStatements

Opps, should be preparedStatement = conn.prepareStatement(todo); That's what happen when you type at work during lunch break...

Opps, should be preparedStatement = conn.prepareStatement(todo); That's what happen when you type at work during lunch break...

Ok, thanx I am reading about preparedstatements now.
Trying out what you say above, the following error occurs:

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 '?,?,?,?,?)' at line 1

it seems like there is something wrong with my code near the question marks:

conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "Mg78QnuE"); 
			String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost)" + "values (?,?,?,?,?)");
			PreparedStatement statement = conn.prepareStatement(todo);

Because you are, seemingly, still using the execute methods that take the sql as an argument. Don't do that.

Because you are, seemingly, still using the execute methods that take the sql as an argument. Don't do that.

Ok, I use preparedstatement:

public void connect(ModelNY modelNY) {		  
		Connection conn = null;		  
		try { 		      
			Class.forName("com.mysql.jdbc.Driver").newInstance();		      
			conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "Mg78QnuE"); 
			String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost)" + "values (?,?,?,?,?)");
			PreparedStatement statement = conn.prepareStatement(todo);	      
			statement.setString(1, modelNY.getPersonID());		      
			statement.setString(2, modelNY.getFName());		      
			statement.setString(3, modelNY.getLName());		      
			statement.setString(4, modelNY.getAddress());		      
			statement.setString(5, modelNY.getEmail());	          
			statement.executeUpdate(todo);

What you are saying is that

statement.executeUpdate(todo);

should not have been done?
What I can read out of the docs you pointed me to is that something like this should be done:

PreparedStatement updateSales = null;
    PreparedStatement updateTotal = null;

    String updateString = "update " + dbName + ".COFFEES " +
                          "set SALES = ? where COF_NAME = ?";

    String updateStatement = "update " + dbName + ".COFFEES " +
                             "set TOTAL = TOTAL + ? where COF_NAME = ?";

    try {
      con.setAutoCommit(false);
      updateSales = con.prepareStatement(updateString);
      updateTotal = con.prepareStatement(updateStatement);

      for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
        updateSales.setInt(1, e.getValue().intValue());
        updateSales.setString(2, e.getKey());
        updateSales.executeUpdate();

        updateTotal.setInt(1, e.getValue().intValue());
        updateTotal.setString(2, e.getKey());
        updateTotal.executeUpdate();
        con.commit();

So if I convert my todo string to something like this:

String updateString = "update " + dbName + ".COFFEES " +
                          "set SALES = ? where COF_NAME = ?";

    String updateStatement = "update " + dbName + ".COFFEES " +
                             "set TOTAL = TOTAL + ? where COF_NAME = ?";

and then say:

updateSales = con.prepareStatement(updateString);
      updateTotal = con.prepareStatement(updateStatement);

it is preparedstatement?

If this is so, I think it is difficult to "translate"

String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost)" + "values (?,?,?,?,?)");
			PreparedStatement statement = conn.prepareStatement(todo);	      
			statement.setString(1, modelNY.getPersonID());		      
			statement.setString(2, modelNY.getFName());		      
			statement.setString(3, modelNY.getLName());		      
			statement.setString(4, modelNY.getAddress());		      
			statement.setString(5, modelNY.getEmail());

into

updateString

and

updateStatement

Cheers!

Is this more like it:

public class ConnectToMySQL {
	public void connect(ModelNY modelNY) {	
		
		PreparedStatement pstmnt = null;
		
		String insertString = "INSERT INTO " + //test + ".idPersoner " + ".forNavn " + ".etterNavn " + ".adresse " + ".epost "
		"values (?,?,?,?,?)";

		Connection conn = null;		  
			try {
			      conn.setAutoCommit(false);
			      pstmnt = conn.prepareStatement(insertString);

			      insertString.executeUpdate();
			      conn.commit();


			
		    } catch(Exception e) {
		    	e.printStackTrace();
			}
		    
		    finally {
		    	try 	{
		    		if(conn != null)
		    			conn.close();
		    	} catch(SQLException e) {}
		    }
		}	
	
	}

Not dificult to translate at all. every place where you have a "?" you need to use a "set" statement and then simply call executeUpdate or executeQuery. I really don't know what the problem with that is. It is still looking as though you are taking the one example given above and still haven't bothered to either look at the tutorial or the api docs. I gave you that information for you to use not for you to ignore. If you're not willing to do that I don't know that I am willing to help.

Not dificult to translate at all. every place where you have a "?" you need to use a "set" statement and then simply call executeUpdate or executeQuery. I really don't know what the problem with that is. It is still looking as though you are taking the one example given above and still haven't bothered to either look at the tutorial or the api docs. I gave you that information for you to use not for you to ignore. If you're not willing to do that I don't know that I am willing to help.

Isn't that what I did here?

try { 		      
			Class.forName("com.mysql.jdbc.Driver").newInstance();		      
			conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "Mg78QnuE"); 
			String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost)" + "values (?,?,?,?,?)");
			PreparedStatement statement = conn.prepareStatement(todo);	      
			statement.setString(1, modelNY.getPersonID());		      
			statement.setString(2, modelNY.getFName());		      
			statement.setString(3, modelNY.getLName());		      
			statement.setString(4, modelNY.getAddress());		      
			statement.setString(5, modelNY.getEmail());	          
			statement.executeUpdate(todo);

Like I said, you are still using the execute methods where you pass the sql as an argument

statement.executeUpdate(todo);

don't do that.

Edit: If I must spell it out, do

statement.executeUpdate();

and I hope that they are all char/varchar fields.

Hmmm, please nothing to your topics

1/ maybe open connection on App startUp, close that on App Exit, to avoid long task during ActionPerformed (from JButton???), in your case GUI probably freeze for second and more ...
2/ there nothing about Object (mo), if is TableModel, TreeModel then you can directly (in Sql statement block) upload value into Vector or another arry (depends of your Model),
3/ if your model contains more than one row then you have to iterate or loop throught model rows (depends of model and JComponents)
4/ search for PreparedStatement
5/ in this case isn't necessary past probably huge Object between plain voids
6/ whats your question exactly, because there is (maybe) lost of problems with basic definitions for Array, JComponents, AbstractClass and your problem is concerning with SQL systax & JDBC, not about passing any Object

Hello, thank you for the tips. I am new this so it is greatly appreciated.
I am curious how would you solve the connect at startup? I guess I want to have it into my main method:

//main
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

I have tried this but the problem seems to be that I cant remove the connection pieces from this code without problems:

public void connect(ModelNY modelNY) {	
		Connection conn = null;		  
		try { 		      
			Class.forName("com.mysql.jdbc.Driver").newInstance();		      
			conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "Mg78QnuE"); 
			String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost)"+"values (?,?,?,?,?)");
			PreparedStatement statement = conn.prepareStatement(todo);	      
			statement.setString(1, modelNY.getPersonID());		      
			statement.setString(2, modelNY.getFName());		      
			statement.setString(3, modelNY.getLName());		      
			statement.setString(4, modelNY.getAddress());		      
			statement.setString(5, modelNY.getEmail());
			statement.executeUpdate();
		    } catch(Exception e)

I was thinking that i could make one method 'connect' and one method 'insert' with the first one containing

Class.forName("com.mysql.jdbc.Driver").newInstance();		      
			conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "Mg78QnuE");

and the second one containing

String todo = ("INSERT INTO personer(idPersoner, forNavn, etterNavn, adresse, epost)"+"values (?,?,?,?,?)");
			PreparedStatement statement = conn.prepareStatement(todo);	      
			statement.setString(1, modelNY.getPersonID());		      
			statement.setString(2, modelNY.getFName());		      
			statement.setString(3, modelNY.getLName());		      
			statement.setString(4, modelNY.getAddress());		      
			statement.setString(5, modelNY.getEmail());
			statement.executeUpdate();

good idea? Or how would you solve it better?

Thank You!

1/ don't pass any Object (if probably will be huge)
2/ search for using try - catch - finally block
3/ anything with statement or prepared statements close just in finally block, because its work if is correct, same on error
4/ don't forget close statement or prepared statements, because this object never gone from Used Memory, because you are using 3rd. party (linked or imported *.jar file), if not your used Memory will be raised and raised, and .... so on
5/ please search for usinng SQL Statement and Prepared Statement, there are tons of examples, try and compare
6 as you has been noticed you probably ignore Data Type defined in Database, Java knows majorities of ..., be sure that with MySql you can put and mix Data type
(psmt.setInt, psmt.setDouble, psmt.setString) just for Date you have to use setTimestampt
7/ for another Db Engine you have to very strict with Data Type, and hmmm nothing....

I'm sure that I can't hepl you with that, but nobody know,

learn how to debug you code or methods

import java.awt.Color;
import java.awt.Component;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;

public class StrippedTable {

    private static final long serialVersionUID = 1L;
    private JScrollPane jSp_StripedTable;
    private JTable jTb_StripedTable;
    private JFrame frm;
    private String IsConnDb = "No";
    private PreparedStatement pstmt = null;
    //
    private String driverDajOkno = "com.mysql.jdbc.Driver";
    private Connection dbConn = null;

    public StrippedTable() {
        initComponents();//initialize components        
        jTb_StripedTable.setDefaultRenderer(Integer.class, new StrippedRenderer());//set custom renderer to table
        jTb_StripedTable.setDefaultRenderer(String.class, new StrippedRenderer());
        jTb_StripedTable.setDefaultEditor(Integer.class, new StrippedEditor());
        jTb_StripedTable.setDefaultEditor(String.class, new StrippedEditor());//set custom editor to table
    }

    private void initComponents() {
        jSp_StripedTable = new JScrollPane();
        jTb_StripedTable = new JTable();
        jTb_StripedTable.setModel(new javax.swing.table.DefaultTableModel(//create a new model and set to table
                new Object[][]{{new Integer(1), "James", "New york", "12345678"},
                    {new Integer(2), "Andrew", "Captown", "23568941"}, {new Integer(3), "Jhon", "Mascow", "89745135"},
                    {new Integer(4), "Domnick", "Colonge", "45786124"}},
                new String[]{"No", "Name", "Address", "Tel."}) {

            private static final long serialVersionUID = 1L;
            Class[] types = new Class[]{java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class};

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }
        });
        jTb_StripedTable.setRowHeight(20);
        jSp_StripedTable.setViewportView(jTb_StripedTable);
        frm = new JFrame();
        frm.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        WindowListener exitListener = new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                int confirm = JOptionPane.showOptionDialog(frm, "Are You Sure to Close Application?", "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (confirm == 0) {
                    frm.setVisible(false);
                    if (IsConnDb.equals("Yes")) {
                        try {
                            closeDbConn();
                        } catch (SQLException ex) {
                            Logger.getLogger(StrippedTable.class.getName()).log(Level.SEVERE, null, ex);
                            System.exit(0);
                        }
                        System.exit(0);
                    } else {
                        System.exit(0);
                    }
                }
            }
        };
        frm.addWindowListener(exitListener);
        frm.setTitle("Striped Table Example");
        frm.add(jSp_StripedTable, java.awt.BorderLayout.CENTER);
        frm.pack();
        //Conn();
        Runnable doRun = new Runnable() {

            @Override
            public void run() {
                visibleFrame();
            }
        };
        SwingUtilities.invokeLater(doRun);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                StrippedTable strippedTable = new StrippedTable();
            }
        });
    }

    public void Conn() {
        IsConnDb = "No";
        try {
            if (dbConn == null || dbConn.isClosed()) {
                //create connection
                IsConnDb = "Yes"; // or use boolean value
                JOptionPane.showMessageDialog(frm, "\n" + "\n" + "Database connection with Su....");
            }
        } catch (InstantiationException e) {
            JOptionPane.showMessageDialog(frm, e + "\n" + "Communications with Database or Table was broken");
        } catch (IllegalAccessException e) {
            JOptionPane.showMessageDialog(frm, e + "\n" + "Communications with Database or Table was broken");
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(frm, e + "\n" + "Communications with Database or Table was broken");
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(frm, e + "\n" + "Communications with Database or Table was broken");
        }
    }

    public void closeDbConn() throws SQLException {
        try {
            if (!dbConn.isClosed()) {
                dbConn.close();
                IsConnDb = "No";
                JOptionPane.showMessageDialog(frm, "\n" + "\n" + "Connection closed with Su....");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            IsConnDb = "No";
            JOptionPane.showMessageDialog(frm, e + "\n" + "Connection closed with Error");
        }
    }

    public void visibleFrame() {
        Runnable doRun = new Runnable() {

            @Override
            public void run() {
                frm.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(doRun);
    }

    private class StrippedRenderer extends DefaultTableCellRenderer {// custom renderer

        private static final long serialVersionUID = 1L;
        private Color color1 = new Color(255, 255, 204);
        private Color color2 = Color.WHITE;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (row % 2 == 0) {
                c.setBackground(color1);
            } else {
                c.setBackground(color2);
            }
            return c;
        }
    }

    private class StrippedEditor extends DefaultCellEditor {//custom editor

        private static final long serialVersionUID = 1L;

        public StrippedEditor() {
            super(new GradientField());
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            GradientField gR_field = (GradientField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
            gR_field.setOpaque(false);
            return gR_field;
        }
    }

    private class GradientField extends JTextField {//custom textfield used in editor

        private static final long serialVersionUID = 1L;
        private Color color1 = new Color(255, 255, 204);
        private Color color2 = Color.PINK;

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D gfx = (Graphics2D) g.create();
            GradientPaint gradient = new GradientPaint(0, 0, color1, 0, getHeight() / 2, color2, true);
            gfx.setPaint(gradient);
            gfx.fillRect(0, 0, getWidth(), getHeight());
            gfx.dispose();
            super.paintComponent(g);
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.