Using Java to Write to a Database – Part 1

Writing to a database is one of the most important actions of any programme. Being able to store data independently of the application is useful for many reasons;

  • The data can be accessed by other applications, such as mobile
  • The application can be updated without affecting the data
  • Database server performance can be upgraded without affecting the application

And many more…

If you have read my other blogs you will know that I use Tomcat for my application servers, however an application server is not required for an application to run. Mobile application, for example, run (mostly) natively on the device. I also use NetBeans as my IDE.

What is needed? The main Library you will need is the vendor specific database driver. These are also known as JDBC (Java Database Connectivity) drivers when coding in Java.

In this example I will use MySQL which is a free and open source database. You can download it from https://www.mysql.com/downloads/  I will not go into the installation and setup of the database server in this blog. The packages are very easy to use, with a next, next, next type installer.

Once you have your server installed, from a command line, log into the database server.

mysql -u root -p

After you have logged into the database server, you will need to create a database.

CREATE DATABASE petstore;

Now tell the system you want to use the new database.

USE petstore;

A database is a collection of tables, views and other functions. You are going to need somewhere to put the data, a table.

CREATE TABLE pet (name VARCHAR(20), kind VARCHAR(20));

Have a look at your newly created table.

SHOW TABLES;
DESCRIBE pet;

OK, you have a database, so let’s connect to it from your application! In part 2…

One thought on “Using Java to Write to a Database – Part 1

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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