0

I'm doing a sample project using jdbc driver. My problem is if I enter a null in my 2 textfield. The null should not be load into the database? Is there anyway how to avoid inserting a empty field in database? Any help will appreciate.

//Execute a query
System.out.println("Creating Statement..");
String query = "INSERT INTO INFO (FIRSTNAME,LASTNAME) VALUES (?,?)";
myStatement = con.prepareStatement(query);

myStatement.setString(1, firstnameTf.getText());
myStatement.setString(2, lastnameTf.getText());
myStatement.executeUpdate();

if (firstnameTf.getText().isEmpty() || lastnameTf.getText().isEmpty()){
    JOptionPane.showMessageDialog(null, "Please Insert");
}

myStatement.close();
con.close();
2
  • What is the schema for the table INFO? The simplest way is to declare the names as NOT NULL - you will get an exception if you try to insert null. Commented Feb 27, 2016 at 18:51
  • Add NOT NULL check in database it will throw an exception and catch it in catch block and print any msg Commented Feb 27, 2016 at 18:54

1 Answer 1

1

You could also use this

if (firstnameTf.getText().isEmpty() || lastnameTf.getText().isEmpty()){
        JOptionPane.showMessageDialog(null, "Please Insert");
    } 



else{
          myStatement =con.prepareStatement(query);

           myStatement.setString(1,firstnameTf.getText());
           myStatement.setString(2, lastnameTf.getText());
           myStatement.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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.