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();
            }
3
  • 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); Commented Sep 25, 2018 at 13:28
  • If you have to cast Statment, you must have the wrong imports. Commented Sep 25, 2018 at 13:29
  • 1
    Please see regarding MySQL Injection here: stackoverflow.com/a/60496/2430549 Commented Sep 25, 2018 at 13:36

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.