0

I'm learning to work with mysql database and now trying to populate statement with text from textfield. The program is phone book and strings are name, surname and telephone number which must be writen in textfield and then added to statement for import in database. So, for now I have this, but not working because statement dont even recognize strings as value.. any ideas what to use/write?

if("Potvrdi".equals(buttonLabel)) {

            String ime = a.getText();
            String prezime = b.getText();
            String broj = c.getText();

            Connection conn = dc.connect();
            Statement st = (Statement) conn.createStatement(); 
            st.executeUpdate("INSERT INTO imenik VALUES (ime,prezime,broj)");
            conn.close();
            }
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
  • 3
    You should use PreparedStatement instead of Statement. PreparedStatement stmt =con.prepareStatement("INSERT INTO imenik VALUES (?, ?, ?)"); stmt.setString(1, ime); stmt.setString(2, prezime); stmt.setString(3, broj); – Oleksandr Riznyk Sep 25 '18 at 13:28
  • If you have to cast `Statment`, you must have the wrong imports. – SedJ601 Sep 25 '18 at 13:29
  • 1
    Please see regarding MySQL Injection here: https://stackoverflow.com/a/60496/2430549 – HoldOffHunger Sep 25 '18 at 13:36

1 Answers1

2

Using prepare statement,

String insertTableSQL = "INSERT INTO imenik VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
preparedStatement.setString(1, ime);
preparedStatement.setString(2, prezime);
preparedStatement.setString(3, broj);
// execute insert
preparedStatement .executeUpdate();
benjamin c
  • 2,278
  • 15
  • 25