JDBC Lab Manual 1.0 Student Version
JDBC Lab Manual 1.0 Student Version
Yared Y.
November 2023
Steps
Download the MySQL connector Java driver in mvnrepository.com (or you can
just use Maven build tool and the configure it in the pom.xml file)
JDBC Connectivity Setup in Eclipse
Prerequisite to understand Java Database Connectivity with MySQL:-
3. To set up the connectivity user should have MySQL Connector to the Java (JAR
file), the ‘JAR’ file can be found in mvnrepository.com (or you can download it
manually. That is optional.)
1. Download the MySQL Connector/J JDBC driver from the official MySQL website
(https://dev.mysql.com/downloads/connector/j/). Or You can visit
mvnrepository.com and search for MySQL driver.
2. Extract the downloaded zip file.
3. In Eclipse, right-click on your project in the "Package Explorer" and select
"Properties."
4. In the project properties window, go to "Java Build Path."
5. Click on the "Libraries" tab.
6. Click "Add External JARs" and navigate to the location where you extracted the
MySQL Connector/J JAR file.
7. Select the JAR file and click "Open."
8. Click "Apply and Close."
You can download the latest version:
Download the JAR file:
Right click on the project folder, select Build Path, and from the submenu select
Add External Archives...
In the JAR Selection panel that comes up, navigate to the folder where the JAR file
you downloaded exists.
Note:
JDBC Drivers:
First step is to load or register the JDBC driver for the database.
Class class provides forName() method to dynamically load the driver class.
Syntax:
Class.forName("driverClassName");
• com.mysql.cj: This is the package name where the MySQL Connector/J (JDBC
driver for MySQL) classes are located.
• jdbc: This is a subpackage within com.mysql.cj that contains the JDBC-related
classes.
• Driver: This is the name of the class that implements the JDBC driver for MySQL.
1. Loading the JDBC Driver: Before you can connect to a specific database using
JDBC, you need to load the JDBC driver class that corresponds to that database.
Different databases have their own JDBC driver classes. In the example provided
earlier (Class.forName("com.mysql.cj.jdbc.Driver")), "com.mysql.cj.jdbc.Driver" is
the fully qualified class name for the MySQL JDBC driver.
By loading this class using Class.forName, you make it available for use in your
application.
2. Driver Registration: When you call Class.forName with the appropriate driver
class name, the driver class is loaded and registered with the DriverManager. The
DriverManager is a part of the JDBC API and is responsible for managing a list of
database drivers. Registering the driver allows the DriverManager to recognize it
and use it for database connections.
It's worth noting that starting with Java 6 and JDBC 4.0, the Class.forName
method is no longer required to load the driver explicitly. The driver is typically
loaded and registered automatically when you place the JDBC driver JAR file on
the classpath. However, in older or non-standard scenarios, you may still encounter
Class.forName being used to load the driver class.
Establish a connection to the database:
Before performing any database operation via JDBC, we have to open a database
connection. To open a database connection we can call getConnection() method of
DriverManager class.
Syntax:
try {
Class.forName(driver); //optional
System.out.println("Established Connection");
}catch (Exception e) {
Database URL (Uniform Resource Locator): The database URL is a string that
specifies the location and configuration of the database you want to connect to.
The format of the URL depends on the database you are using. In the example
provided earlier, the MySQL database URL looks like this:
```
String url = "jdbc:mysql://localhost:3306/your_database";
```
- `"jdbc:mysql://"`: This part indicates the JDBC protocol and the database type
(MySQL).
- `"localhost:3306"`: This specifies the hostname (or IP address) and the port
number of the database server.
- `"your_database"`: This is the name of the specific database you want to connect
to.
For MySQL, the URL format is often jdbc:mysql://hostname:port/database. This URL
provides information about the database server, the port it's listening on, and the
specific database you want to access.
Username and Password: You typically need to provide a username and
password to access the database. These credentials are used for authentication.
Establishing the Connection: The `DriverManager.getConnection` method is
used to establish a connection to the database. It takes the database URL,
username, and password as arguments and returns a `Connection` object.
```
// Close the connection when done
connection.close();
```
Failure to close the connection can lead to resource leaks and decreased
performance, so it's essential to always close the connection when you no longer
need it. Typically, this is done within a `finally` block to ensure that the connection
is closed even if an exception is thrown during database operations.
Keep in mind that handling exceptions and errors properly, such as catching
`SQLException`, is crucial when working with database connections to ensure that
your application handles any potential issues gracefully.
Creating a database
To create a new database in MySQL using Java and JDBC, you need to execute a
SQL query that creates the database. Here's an example of how to do it:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
// Create a statement
statement.executeUpdate(createDatabaseSQL);
// close resources
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
This Java code demonstrates how to use JDBC (Java Database Connectivity) to
create a new database using MySQL. I'll explain the important ones:
`Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "root");`
- This line establishes a database connection using the
`DriverManager.getConnection` method. It connects to a MySQL database running
on the local machine at port 3306 with the username "root" and password "root".
The connection object is stored in the `connection` variable.
`statement.execute(query);`
- This line executes the SQL query stored in the `query` string using the
`execute` method of the `Statement` object (`statement`). This query creates the
"new_database" database.
CREATE TABLE
package com.itsc;
import java.sql.*;
"first_name varchar(255)," +
"last_name varchar(255)," +
"school varchar(255)," +
"hire_date date," +
statement.executeUpdate(createTableSQL);
}
INSERT DATA INTO TABLE
To populate the "teachers" table with the provided set of data, you can use SQL INSERT
statements. Here's a Java JDBC example to insert the data into the "teachers" table:
package com.itsc;
import java.sql.*;
"first_name varchar(255)," +
"last_name varchar(255)," +
"school varchar(255)," +
"hire_date date," +
statement.executeUpdate(createTableSQL);
String[] insertStatements = {
"insert into teacher1(first_name, last_name, school,
hire_date, salary) values('Aster', 'Nega', 'Yekatit 12', '2021-01-01',
8000)",
};
statement.executeUpdate(stmt);
STATEMENT
In Java, a Statement is an interface provided by the JDBC (Java Database Connectivity) API
that allows you to execute SQL queries against a database.
Example: Given the following teachers table, write a java code to retrieve the data
package com.itsc;
import java.sql.*;
while(res.next()) {
int id = res.getInt("id");
System.out.println("...............");
}
In JDBC, the `Statement` interface provides several methods for executing SQL
queries and commands. Here are some of the key methods related to `Statement`:
1. executeQuery(String sql):
- Executes a SQL query that returns a `ResultSet`. Typically used for `SELECT`
statements to retrieve data.
2. executeUpdate(String sql):
- Executes an SQL statement (typically `INSERT`, `UPDATE`, or `DELETE`)
and returns the number of affected rows. It's used for data manipulation operations.
3. execute(String sql):
- Executes any SQL statement (either a query or a command) without returning a
result. It's used for a wide range of SQL operations.
Practice Time:
- Calculate and display the average grade of all students in the table.
Here's a sample Java program to help you get started with these tasks:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
try {
// Task 1: Connect to MySQL Database, Create Database, and Table
Connection connection = DriverManager.getConnection(url, username,
password);
Statement statement = connection.createStatement();
statement.execute("CREATE TABLE IF NOT EXISTS students (id INT
PRIMARY KEY, firstname VARCHAR(255), lastname VARCHAR(255), grade
INT)");
} catch (Exception e) {
e.printStackTrace();
}
}
while (resultSet.next()) {
int id = resultSet.getInt("id");
String firstname = resultSet.getString("firstname");
String lastname = resultSet.getString("lastname");
int grade = resultSet.getInt("grade");
System.out.println("ID: " + id + ", Name: " + firstname + " " + lastname
+ ", Grade: " + grade);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void updateStudentName(Connection connection, int id, String
newFirstName) {
try {
PreparedStatement updateStatement =
connection.prepareStatement("UPDATE students SET firstname = ? WHERE id =
?");
updateStatement.setString(1, newFirstName);
updateStatement.setInt(2, id);
updateStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
while (resultSet.next()) {
double averageGrade = resultSet.getDouble("average_grade");
System.out.println("Average Grade: " + averageGrade);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```