简体   繁体   中英

What am I doing wrong in inserting data to mysql table?

After executing code I get the Data saved message but no data is recorded in my clients table? I'm new to databases with Java, What am I doing wrong or how can I fix my code?

    String sqlUrl = "jdbc:mysql://localhost:3306/clientinformation";
    String user = "root";
    String pass = "root";
    String name = firstName.getText();
    String lname = lastName.getText();
    String cEmail = email.getText();
    String rate = rateDbl.getText();
    String cUrl = url.getText();
    try {
        Connection con = DriverManager.getConnection(sqlUrl, user, pass);
        PreparedStatement st = con.prepareStatement("insert into clients 
                values('"+name+"', '"+lname+"', "
                + "'"+cEmail+"', '"+rate+"', '"+cUrl+"')");
        JOptionPane.showMessageDialog(null, "Data saved!");
    } catch (SQLException ex) {
        Logger.getLogger(newClient.class.getName()).log(Level.SEVERE, null, ex);
    }    

What am I doing wrong

Well, you're building your SQL statement by concatenating values. That leads to SQL injection attacks - amongst other issues. Fortunately, that hasn't actually created a problem just yet - because you're never executing your statement.

You need to:

  • Parameterize your SQL, to avoid a SQL injection attack - use question marks for the parameters, and then use st.setString to set each parameter:

     Connection con = DriverManager.getConnection(sqlUrl, user, pass); PreparedStatement st = con.prepareStatement( "insert into clients values (?, ?, ?, ?, ?)"); st.setString(1, name); st.setString(2, lname); st.setString(3, cEmail); st.setString(4, rate); // Should this really be a string? st.setString(5, cUrl); st.executeUpdate(); JOptionPane.showMessageDialog(null, "Data saved!"); 
  • Call st.executeUpdate before you display the dialog box. (Ideally you shouldn't be mixing UI and data access in the same method, but...)

Please make the changes in that order though - do not just add a call to st.executeUpdate , or you've got a horrible security hole in your app.

The reason you're not seeing the data is you prepare the statement but never execute it. Call st.execute(); or st.executeUpdate(); to execute it.


Separately, though: That code is subject to SQL injection (attacks or otherwise); fun illustration here . Half the point of prepared statements is to protect against them. Use the parameters that prepared statements give you:

PreparedStatement st = con.prepareStatement("insert into clients values(?, ?, ?, ?, ?)");
int n = 1;
st.setString(n++, name);
st.setString(n++, lname);
st.setString(n++, cEmail);
st.setString(n++, rate);
st.setString(n++, cUrl);
// And then the missing execute
st.execute();

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