Step 1: Install Java JDK
Install the Java Development Kit (JDK) on your system.
Verify the installation using:
The Java compiler and runtime are required to develop and execute JDBC programs.
Step 2: Install a Database
Install a relational database such as:
- MySQL
- Oracle Database
- PostgreSQL
- SQL Server
For beginners, MySQL is commonly used for JDBC practice.
Step 3: Create a Database
Create a database that the Java application will access.
Example:
Select the database:
Step 4: Create a Table
Create a table for storing application data.
Step 5: Add the JDBC Driver
i. Download and add the JDBC driver corresponding to your database.
-
Go to the official download page: dev.mysql.com/downloads/connector/j
-
In the Select Operating System dropdown, choose Platform Independent.
-
Download the ZIP Archive (
mysql-connector-j-8.x.x.zip). -
Extract the
.zipfile. Inside the extracted folder, find the file namedmysql-connector-j-8.x.x.jar(ormysql-connector-java-8.x.x.jar).
ii. When using set CLASSPATH, you must include both the exact JAR filename and the current directory (.) so Java can find both the driver and your .class files.
Assuming:
-
Your JAR file is:
D:\programs\mysql-connector-j-8.3.0.jar -
Your Java file is:
D:\programs\MyApp.java
Open Command Prompt and run:
D:
cd D:\programs
set classpath to current folder (.) and the exact JAR name like below
set classpath=D:\programs\mysql–connector–j-8.3.0.jar;
iii. Compile and Run Your Program
javac MyApp.java
java MyApp
Step 6: Import JDBC Classes
Import the required classes from the java.sql package.
For more database operations, you may also import:
Step 7: Define the Database URL
Specify the location of the database using a JDBC URL.
For MySQL:
The URL contains:
| Part | Meaning |
|---|---|
jdbc |
Indicates that JDBC is being used |
mysql |
Specifies the database type |
localhost |
Database server running on the local machine |
3306 |
Default MySQL port |
jdbc_demo |
Database name |
Step 8: Provide Database Credentials
Specify the username and password used to access the database.
Step 9: Establish the Database Connection
Use DriverManager.getConnection() to establish a connection.
If the connection is successful, the Java application can communicate with the database.
Step 10: Create a SQL Statement
Create a Statement or PreparedStatement to execute SQL commands.
Example:
Step 11: Execute the SQL Query
Execute a SQL query using the statement.
The ResultSet contains the records returned by the database.
Step 12: Process the Result
Read the records from the ResultSet.
Step 13: Close JDBC Resources
After completing the database operation, close the resources.
In modern Java, try-with-resources is preferred because it automatically closes JDBC resources.
