Search code examples
javadatabasejtextfield

How to restrict JtextField from putting extra spaces in database?


Whenever I add values in database through JtexField it saves extra spaces in the sql database is there any way to restrict wide spaces and save only the text added in TextField?

try {
  String query = "insert into items (item_name, category_id, item_price, item_description, stock) Values (?,?,?,?,?) ;";
  PreparedStatement pst = con.prepareStatement(query);
  pst.setString(1, textField_1.getText());
  pst.setString(2, textField_2.getText());
  pst.setString(3, textField_3.getText());
  pst.setString(4, textField_4.getText());
  pst.setString(5, textField_5.getText());

  pst.execute();
  JOptionPane.showMessageDialog(null, "Data Saved");
  pst.close();
 } catch (Exception e) {
  e.printStackTrace();
 }

spaces like this enter image description here

Trim function enter image description here


Solution

  • Eliminates leading and trailing spaces:

    1. Using String's trim() method

      textField_1.getText().trim();

    2. Using Regex

      textField_1.getText().replaceAll("^\\s+|\\s+$", "");