Access to databases with Java.

Access to databases with Java.

We will talk about how to connect to a database with Java,

To do this we will use the JDBC (Java DataBase Connectivity) which is nothing else than java database connection.

1 : Establish the connection.

We have to start at the beginning and so we will have to use a database, here I will use the Dragon database.

then place in the library of your java project a :

« mysql-connector-java-version.jar ».

And then we can begin our Java project !

Once we have our database we will create a Java project with Maven and we will add a dependency that will allow us to connect with a MySQL type database.

And so to establish a connection we will have to tell java that we want to connect. To do this we’ll use Connection which will ask us for the database information like its address, username and password.

As you can see the getConnection forces us to place the code in a try/catch or we can return the error. In our example we will place it in a try/catch block as follows.

2- Retrieving data

Once the connection is established we will look for information in our database and display it in the console.

To do this we will need a statement

The statement will allow us to execute SQL queries to the database but we will need a resultset which will contain the results of our query so we will add it. In our example we will make a query to retrieve the all data.

Which gives us the following result :

the program will then query the database until it retrieves all the data in the form of an arrayList. It will not remain any more but to make the methods to display these data!


Patrick Arnaud


Laisser un commentaire