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:

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