Java JDBC Tutorial – Inserting Data with User Input

In this blog post, I’ll show you how to insert data into the database with user input. When you run the program, it will prompt you to enter your last name, first name and email address. Here’s a sample run of the app:

Enter your last name: Davis

Enter your first name: Sammy

Enter your email: sammy@test.com

Insert complete.

To accomplish this, you’ll make use of the Scanner class that is defined in the java.util package. This class can read input as Strings and Java primitives. In this example, we’ll just use it to read in the last name, first name and email. Here’s the code snippet:

Now, we can use this in our JDBC code to insert data supplied by the user. We could just perform a String concatenation with the values, but that would open us up to SQL injection attacks. Instead, we’ll make use of Prepared Statements that is explained in detail in another blog post here: Java JDBC Prepared Statements.

So here’s the code for setting up the prepared statement and setting the input values from the user.

That’s it. Those are the steps for inserting data into the database with user input.

Download Source Code

Did you like my blog post?

Signup now and receive an email when I publish new luv2code content.

I agree to have my personal information transfered to AWeber ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

7 Comments

  1. Comments  Amos   |  Sunday, 06 November 2016 at 6:46 am

    Thank you. it is very helpful.

  2. Comments  Gautam   |  Tuesday, 21 February 2017 at 2:35 am

    Thanks a lot. You save my day.

  3. Comments  norita teo   |  Wednesday, 03 May 2017 at 10:12 pm

    thank you life saver!!!!

  4. Comments  Chad Darby   |  Sunday, 28 May 2017 at 8:47 am

    you are welcome!

  5. Comments  mahesh veer   |  Wednesday, 08 November 2017 at 5:39 am

    Helpful Post this helped Me a lot

  6. Comments  Chad Darby   |  Sunday, 26 November 2017 at 6:16 pm

    You are welcome Mahesh. thanks for the kind words 🙂

  7. Comments  Mohammad Goudarzi   |  Saturday, 20 April 2019 at 5:07 am

    You solved my problem :))))))
    Thank you :))))

Leave a Reply