Using Java to Write to a Database – Part 2

Continuing from Part 1

In part 1 we created the simplest of databases, nothing more than a table with 2 columns.

There are two main ways to write an application in Java, in my opinion of course… the first is for native applications, those applications that run directly on your desktop or mobile device. The second is an application that runs on top of an application server, such as Tomcat. Tomcat would then, normally, provide a way to interface with the application through web pages or APIs.

Of course it is possible to run an application on an application server with no interfaces. This could be for tasks such as generating reports as a scheduled service and sending them via email. Therefore, no interaction and no interface.

So, in this part we will first focus on the most common use, Web Applications.

In this part we will use a JDBC connection so the data can be accessed in our applications.

For Connecting to a database with Tomcat <- use this link as it is the foundation for the rest of this post.

Now, hopefully, you have a database and a simple web application to pull data from that database. The next step is the purpose of this post, writing data back to the database.

In the same way you retrieved data, to write data back just takes a couple more steps.

public void getEntityTableName() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(“jdbc/myDatabase”);
EntityManager em = emf.createEntityManager();
try {
PetTable petTable = new PetTable();
EntityTransaction transaction = em.getTransaction();
} catch (Exception e) {
System.out.println(“e = ” + e);
} finally {

The difference is the need to start and end a transaction. When writing data to a transactional database you need to obtain exclusive rights to the table where you are writing data to, just so no one else can write or delete data that you are using. What this also allows is the rolling back of changes if something goes wrong.

EntityTransaction transaction = em.getTransaction();

Make some changes to the database


That’s it, lastly you need to close the connections to the database, otherwise you could spawn multiple connections and cause a denial of service.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s