Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
Connectivity (JDBC)
Advance Programming
JDBC
• JDBC (Java Database Connectivity) API allows Java programs to
connect to databases
• The JVM uses a JDBC driver to translate generalized JDBC calls into
vendor specific database calls
Java Database Driver
• Think of a database as just another device connected to your computer
• like other devices it has a driver program to relieves you of having to do
low level programming to use the database
• the driver provides you with a high level api to the database
• Make sure you install the driver along with the DBMS. (Install connectorJ
for MySQL).
• In order to use this driver in your code, you can add the driver in eclipse by
adding an external jar file containing the library.
• i.e. add the jar file of connectorJ in Project properties of Database project.
Adding the JDBC Driver in intellij
IDEA
Open Project Structure:
• Go to File > Project Structure (or press Ctrl+Alt+Shift+S).
Add the Library:
• In the Project Structure window, select Modules from the left sidebar.
• Select your module (usually named the same as your project).
• Click on the Dependencies tab.
• Click the + icon to add a new dependency and choose JARs or directories.
• Navigate to the location where you downloaded the mysql-connector-java-
x.x.x.jar file and select it.
• Click OK and Apply to add the JDBC driver to your project.
Database Driver
DB Client Server
Java
Application
Data Source
JDBC
JDBC Driver
API
Basic steps to use a database in
Java
1. Load the database driver
2. Establish a connection
3. Create JDBC Statements (SQL queries)
4. Execute JDBC statements
5. Use result sets (tables) to navigate through the results
6. Close the connection
Connecting to a Database
• JDBC Driver – MySQL Server
Class.forName (“com.mysql.cj.jdbc.Driver”);
con = DriverManager.getConnection
(“jdbc:mysql://localhost:3306/databasename”, uid, passwd);
Class.forName (“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection (
“jdbc:oracle:thin:@bonsai.ite.gmu.edu:1521:ite”,
“accountname", “password”);
Create JDBC statement(s)
• java.sql.Statement
• Statement is an interface in the java.sql package.
• It is used to execute SQL statements without any parameters.
Statement stmt = con.createStatement() ;
• PreparedStatement is a subinterface of Statement in the java.sql
package.
• It is used to execute SQL statements that contain parameters.
• It provides built-in protection against SQL injection attacks.
PreparedStatement preparedStatement = con.prepareStatement(sql);
Creating Tables
• Creating a Coffee table
CREATE TABLE COFFEES (COF_NAME VARCHAR(32), ID INTEGER, PRICE FLOAT,
SALES INTEGER, TOTAL INTEGER)
• Statements that create a table, alter a table, or drop a table are all
examples of DDL statements and are executed with the method
executeUpdate