Hello. In this video, we’re going to learn
how to use Java JDBC to insert data into a database. 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. 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. 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. 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. 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. 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. 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, David Brown @foo.com. We were successful. 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.