JDBC Architecture
JDBC (Java Database Connectivity) is an API that allows Java applications to connect with databases. It gives us a standard interface for connecting, querying, and updating databases using SQL.
The main components of JDBC Architecture
1. Java ApplicationThe application that connect with the database using JDBC.
2. Driver Manager
Manages different database drivers and establishes connections.
3. Driver
Translates Java code into database-specific commands.
4. Database
The main database where data is stored.
Statement Class of JDBC
Syntax:
Statement st = con. CreateStatement();
- This is the pre-defined class of JDBC API.
- Statement class is used to execute queries(SQL commands).
Example:
- st.executeUpdate ( " create table emp (------) " );
- st.executeUpdate ( " insert into emp values(------) " );
- st.executeUpdate ( " update emp ------ " );
- st.executeUpdate ( "delete from emp (------) " );
- st.executeUpdate ( " select * from emp (------) " );
Create a Database in the MySQL Workbench
Syntax :
create database database_name;
Example:
create database employee;
CRUD Operations using JDBC
1. Load the driver class
Class.forName("com.mysql.Jdbc.Driver");
2. Establish a connection to the database
Connection con = DriverManager.getConnection("URL", "username", "password" );
---> URL : ("jdbc:mysql://localhost:3306/database name");
---> username: “root”; (according to your username)
---> password: “1234”; (according to your password)
3. Prepare SQL Statement
Statement s = con.createStatement();
4. Execute the query
s.executeUpdate("create table table_Name(columnName datatype(size) constraint)");
Example:
("create table employee(id int(5) primary key, name varchar(15) not null, salary double(7,2)" )
5. Close the Connection
s.close(); con.close();
We will learn briefly about various CRUD operations like Create, Update, and Delete in our next tutorial.
Two Minute Drill
- JDBC Architecture consists of Java Application, Driver Manager, JDBC Driver, and Database.
- CRUD operations (Create, Read, Update, Delete) are performed using Statement in JDBC.
- Always close connections to prevent memory leaks.