Java JDBC Tutorial – Part 2: Insert data into a Database

In this video tutorial, I will show you how to insert data into a database with Java JDBC.

Please subscribe 🙂

 

Video Transcript

Time – 00:00
Hello. In this video, we’re going to learn how to use Java JDBC to insert data into a database.

Time – 00:10
As for as the prep work that you need to have taken care of, you need to make sure that you have a database already installed. In this example, we’re going to use MySQL. Also, you need to make sure you have the JDBC driver installed for your database. In this example, we’re going to make use of a very simple table called employees. This table is going to have four columns. It’s going to have the ID, the last name, the first name and the email address.

Time – 00:44
Now, let’s take a look at this table in our SQL query tool. In this example, I have the employees table. I run and select star against that table, and I have my output. We have three employees in the database right now: John Doe, Mary Public and Susan Queue. Now, if we wanted to actually insert data into the database, we could use the query tool and we could use the statement here. “insert into employees”, specify the columns, last name, first name, email, and then the actual values.

Time – 01:26
What we’re going to do is take this information and actually use it in a Java program. Our basic development process is, first, getting a connection to a database. Second, creating a statement, and third, executing the SQL insert. Let’s move over to our Java development tool.

Time – 01:51
In this application, it’s a very simple project. What we need to do first is get a connection to a database. We’ll have Driver Manager get connection. We give the URL, the user ID and the password. Once we have a connection to the database, then we can create a statement.

Time – 02:16
I’ll say, “myConn.createStatement” and it gives me a blank statement object. Now that I have a statement, I can setup my SQL. The SQL, I will assign it to a string variable. It’s the same SQL we saw in the previous slide. “Insert into employees”, I give the last name, first name, email, and then I’ll also provide the values: Brown for last name, David, and then that person’s email address. Now that I have the SQL, I make use of the statement here, “mystmt.executeupdate” and I pass in the SQL. This will actually execute a SQL code against the database.

Time – 03:03
Then when I’m finished, I’ll just do a system out print line, “Insert Complete”, and then I have my normal exception handler for the code. Let’s go ahead and save this and let’s run it as a Java application.

Time – 03:18
I’ll say execute. Note at the bottom it says, “Insert complete.” Now we can go through and actually check this against our database. If I run the query one more time, and now I can see the statement or the new entry here for our new employee, davidbrown@foo.com. We were successful.

Time – 03:48
Let’s go ahead and wrap up. We were able to insert data into a database using Java JDBC. If you’d like the code examples or more video tutorials, then visit luv2code.com.

Source Code: Driver.java


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Driver {

	public static void main(String[] args) throws SQLException {

		String url = "jdbc:mysql://localhost:3306/demo";
		String user = "student";
		String password = "student";

		Connection myConn = null;
		Statement myStmt = null;

		try {
			// 1. Get a connection to database
			myConn = DriverManager.getConnection(url, user, password);

			// 2. Create a statement
			myStmt = myConn.createStatement();

			// 3. Execute SQL query
			String sql = "insert into employees " + " (last_name, first_name, email)"
					+ " values ('Brown', 'David', 'david.brown@foo.com')";

			myStmt.executeUpdate(sql);

			System.out.println("Insert complete.");
		} catch (Exception exc) {
			exc.printStackTrace();
		} finally {
			if (myStmt != null) {
				myStmt.close();
			}

			if (myConn != null) {
				myConn.close();
			}
		}
	}
}

MySQL Script for Creating the Database table


create database if not exists demo;

use demo;

drop table if exists employees;

CREATE TABLE <code>employees</code> (
<code>id</code> int(11) NOT NULL AUTO_INCREMENT,
<code>last_name</code> varchar(64) DEFAULT NULL,
<code>first_name</code> varchar(64) DEFAULT NULL,
<code>email</code> varchar(64) DEFAULT NULL,
PRIMARY KEY (<code>id</code>)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

INSERT INTO <code>employees</code> (<code>id</code>,<code>last_name</code>,<code>first_name</code>,<code>email</code>) VALUES (1,'Doe','John','john.doe@foo.com');
INSERT INTO <code>employees</code> (<code>id</code>,<code>last_name</code>,<code>first_name</code>,<code>email</code>) VALUES (2,'Public','Mary','mary.public@foo.com');
INSERT INTO <code>employees</code> (<code>id</code>,<code>last_name</code>,<code>first_name</code>,<code>email</code>) VALUES (3,'Queue','Susan','susan.queue@foo.com');

Download Source Code: jdbcdemo-insert.zip

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.

2 Comments

  1. Comments  Jason   |  Monday, 03 November 2014 at 9:23 pm

    Hi, would it be possible to get exact copy of your database, called “Demo”?

  2. Comments  Chad Darby   |  Tuesday, 04 November 2014 at 4:13 am

    Hi Jason,

    I updated the post to include the SQL script. Enjoy 🙂

Leave a Reply