You are on page 1of 48

CSE1007 - JAVA PROGRAMMING

MODULE-5
Accessing Databases using JDBC
connectivity
JDBC

• JDBC is an interface which allows Java code to


execute SQL statements inside relational
databases
• The JDBC API was completely written in Java
language.
• A pure java solution allows JDBC driver to be
automatically downloaded and installed along
with Applets.
• Keep it simple
• High-performance
JDBC Architecture

JDBC Application

JDBC Driver Manager

JDBC Drivers

Application JDBC Driver


Overall Architecture
JDBC in Use

Java JDBC
program driver
connectivity for Oracle
data processing
utilities driver
for Sybase

jdbc-odbc odbc
bridge driver
JDBC APIs
•JDBC is implemented via classes in the java.sql package
Interfaces Classes
CallableStatement DriverManager
Connection Date
DatabaseMetaData Time
Driver Types
PreparedStatement
ResultSet
ResultSetMetaData
Statement
Driver Manager

• DriverManager tries all the drivers


• Uses the first one that works
• When a driver class is first loaded, it registers
itself with the DriverManager
• Therefore, to register a driver, just load it!
Driver Manager

• DriverManager
– Loads, chooses drivers
• Driver
– connects to actual database
• Connection
– a series of SQL statements to and from the DB
• Statement
– a single SQL statement
• ResultSet
– the records returned from a Statement
Driver Manager
–Loads, chooses drivers
DriverManager

Driver
–connects to actual database a series of SQL statements to
and from the DB
Connection

Statement
a single SQL statement

ResultSet
the records returned from a Statement
Driver Manager

creates creates creates


DriveManager Connection Statement ResultSet

SQL data

make link Driver


to driver
SQL data
Basic Steps to access DB using JDBC

•Import the java.sql package


•Load and register the driver
•Establish the connection to the database
•Create a statement
•Execute the statement
•Retrieve the results
•Close the statement and connection
Basic Steps to access DB in Netbeans using JDBC
JDBC URLs

jdbc:subprotocol:source
• Each driver has its own subprotocol
• Each subprotocol has its own syntax for the source
• EX:
jdbc:odbc:DataSource
– jdbc:oracle:thin:@localhost:1521:xe
jdbc:mysql://host[:port]/database
– jdbc:mysql://localhost:3306/stuDB
Driver Manager

Connection getConnection(String url, String user, String password)

• Connects to given JDBC URL with given user


name and password
• Throws java.sql.SQLException
• Returns a Connection object
Connection

• A Connection represents a session with a specific


database.
• Within the context of a Connection, SQL statements
are executed and results are returned.
• Can have multiple connections to a database
• Also provides “metadata” -- information about the
database, tables, and fields
• Also methods to deal with transactions
Obtaining a Connection
try
{
Connection con=null;//Establish a connection
Class.forName("com.mysql.jdbc.Driver").newInstance();//loads the driver
//define the connection properties i.e dbname, username and password
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee1",
"root","");
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
Connection Methods
Statement createStatement()
– returns a new Statement object
– Statement s=con.createStatement();
PreparedStatement prepareStatement(String sql)
– returns a new PreparedStatement object
CallableStatement prepareCall(String sql)
– returns a new CallableStatement object
– Use this when you want to access the database stored
procedures. The CallableStatement interface can also
accept runtime input parameters.
System.out.println("Enter the Name: ");
String name=inp.nextLine();
System.out.println("Enter the Salary: ");
Double sal=inp.nextDouble();
System.out.println("Enter the DOB: ");
String dob=inp.next();
Date date=Date.valueOf(dob);
System.out.println("Enter the yearofExp: ");
int exp=inp.nextInt();

String sql="insert into empinfo values(?,?,?,?);";


PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setDouble(2,sal);
ps.setDate(3, date);
ps.setInt(4,exp);
ps.execute();
Statement
The Statement object provides a ‘workspace’ where SQL queries can
be created and results collected.
Methods
ResultSet executeQuery(String)
– Execute a SQL statement that returns a single ResultSet.
– ResultSet rs=s.executeQuery("select * from empinfo;");
int executeUpdate(String)
– Execute a SQL INSERT, UPDATE or DELETE statement. Returns
the number of rows changed.
– s.executeUpdate("INSERT INTO employee_details
VALUES(6,'Jincy',20, '2000-09-01',25000);");
boolean execute(String)
– Execute a SQL statement that may return multiple results.
– ps.execute();
ResultSet
• A ResultSet provides access to a table of data generated
by executing a Statement.
• Only one ResultSet per Statement can be open at once.
• The table rows are retrieved in sequence.
• A ResultSet maintains a cursor pointing prior to its
current row of data.
• The 'next' method moves the cursor to the next row.
– you can’t rewind
ResultSet Methods
• boolean next()
– activates the next row
– the first call to next() activates the first row
– returns false if there are no more rows
• void close()
– disposes of the ResultSet
– allows you to re-use the Statement that created it
– automatically called by most Statement methods
• int findColumn(String columnName)
– looks up column index given column name
ResultSet Methods

• String getString(int columnIndex)


• boolean getBoolean(int columnIndex)
• byte getByte(int columnIndex)
• short getShort(int columnIndex)
• int getInt(int columnIndex)
• long getLong(int columnIndex)
• float getFloat(int columnIndex)
• double getDouble(int columnIndex)
• Date getDate(int columnIndex)
• Time getTime(int columnIndex)
• Timestamp getTimestamp(int columnIndex)
Interact with the Database

• Drivers are required. Download from here.


• http://dev.mysql.com/downloads/connector/j/
• Procedure to download and add in Library in the below
link
• https://www.youtube.com/watch?v=nW13FmTdkjc&t=
256s
• This is the file after extracting……………
Interact with the Database
Procedure to add the library
• Right the Javafx Application  Add JAR/Folder  select the
connector and click Open
Accessing Databases using JDBC connectivity

• MySQL installation:
https://www.apachefriends.org/download.html
Video link to install XAMPP
https://www.youtube.com/watch?v=N6ENnaRotmo

• To connect Java application with the MySQL


database, we need to follow 5 steps.
• We are going to use MySql as the database.
• So we need to know following information for the
mysql database:
Java Database Connectivity with MySQL
• Driver class: The driver class for the mysql database
is com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the mysql database
Is jdbc:mysql://localhost:3306/StuDB where jdbc is the API,
mysql is the database, localhost is the server name on which
mysql is running, we may also use IP address, 3306 is the port
number and StuDB is the database name. We may use any
database, in such case, we need to replace the StuDB with our
database name.
• Username: The default username for the mysql database is root.
• Password: It is the password given by the user at the time of
installing the mysql database. In this example, we are going to
use root as the password.
Java Database Connectivity with MySQL

SQL
Insert Values

• The INSERT Statement is used to add new rows of data to a table.


• When adding a new row, you should ensure the datatype of the
value and the column matches
• Syntax
INSERT INTO TABLE_NAME (col1, col2, col3,...colN)
VALUES (value1, value2, value3,...valueN);
• Example:
INSERT INTO employee (id, name, dept, age, salary location)
VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);
INSERT INTO employee VALUES (105, 'Srinath', 'Aeronautics',
27, 33000);
Update Query

• The UPDATE Statement is used to modify the existing rows in


a table.
• Syntax:
UPDATE table_name SET column_name1 = value1,
column_name2 = value2, ... [WHERE condition]
• Example:
UPDATE employee SET location ='Mysore' WHERE id =
101;
UPDATE employee SET salary = salary + (salary * 0.2);
Delete Query

• The DELETE Statement is used to delete rows


from a table.
• Syntax:
DELETE FROM table_name [WHERE condition];
• Example:
DELETE FROM employee WHERE id = 100;
Java Database Connectivity with MySQL

• Let's first create a table in the mysql database,


but before creating table, we need to create
database first.
1. Create database StuDB;
2. Use StuDB;
3. create table student(RNo int(15),Name varchar(1
5),School varchar(15), Department
varchar(15));
Java Database Connectivity with MySQL
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
Connecting a Java program to the Database(Insert)
public class jdbcbasic
{
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
IllegalAccessException
import java.sql.Connection;
{ import java.sql.DriverManager;
try { import java.sql.SQLException;
Connection con=null;//Establish a connection import java.sql.Statement;
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();//loads the driver
//define the connection propertiesi.e dbname, username and password
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root",“root");
System.out.println("Connection Successful");
Statement s=con.createStatement(); // insert a record into table
//Execute the Query
s.executeUpdate("INSERT INTO employee_details VALUES(6,'Jincy',20, '2000-09-01',25000);");
System.out.println("Record inserted");
s.close();
con.close();
}catch(SQLException e){
System.out.println(e.getMessage());
} }
Connecting Java program to the Database(update,delete,select)

//To update the records;


s.executeUpdate("Update empinfo set salary=80000 where
empname='Doe';");
//To delete the records;
s.executeUpdate("delete from empinfo where empname='Doe';");
//To select the records;
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("select * from empinfo;");
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getBigDecimal(2)+"
"+rs.getDate(3)+" "+rs.getInt(4));
}
Connecting a Java program to the Database(Select)
Create a new Java class
public class jdbcbasic {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
IllegalAccessException {
try{
Connection con=null;//Establish a connection
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();//loads the driver
//define the connection properties i.e dbname, username and password
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee1","root","");
System.out.println("Connection Successful");
Statement s=con.createStatement(); // insert a record into table
//Execute the Query
ResultSet rs=s.executeQuery("select * from empinfo;");
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getBigDecimal(2)+" "+rs.getDate(3)+" "+rs.getInt(4));
}
s.close();
con.close();
}catch(SQLException e){
System.out.println(e.getMessage());
} } }
Insert the record based on the user input
try{
Connection con=null;
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee1","root","");
System.out.println("Connection Succesfull");
Statement s=con.createStatement(); // insert a record into table
Scanner inp=new Scanner(System.in); System.out.println("Record Inserted successfully");
System.out.println("Enter the Name: "); ps.close();
String name=inp.nextLine(); con.close();
System.out.println("Enter the Salary: "); }
Double sal=inp.nextDouble(); catch(SQLException e){
System.out.println("Enter the DOB: "); System.out.println(e.getMessage());
}
String dob=inp.next();
Date date=Date.valueOf(dob);
System.out.println("Enter the yearofExp: ");
int exp=inp.nextInt();
String sql="insert into empinfo values(?,?,?,?);";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setDouble(2,sal);
ps.setDate(3, date);
ps.setInt(4,exp);
ps.execute();
Update the record based on the user input
//Establish the connection and load the drivers and set the conn properties
Statement s=con.createStatement(); // insert a record into table
Scanner inp=new Scanner(System.in);
System.out.println("Enter the Salary: ");
Double sal=inp.nextDouble();
System.out.println("Enter the Name: ");
String name=inp.next();
String sql="Update empinfo set salary=? where empname=?;";
PreparedStatement ps=con.prepareStatement(sql);
ps.setDouble(1,sal);
ps.setString(2,name);
ps.execute();
System.out.println("Record Updated successfully");
ps.close();
con.close();
Delete the record based on the user input
Statement s=con.createStatement(); // insert a record into table
Scanner inp=new Scanner(System.in);
System.out.println("Enter the Name: ");
String name=inp.next();
String sql="delete from empinfo where empname=?;";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.execute();
System.out.println("Record Deleted successfully");
ps.close();
con.close();
SQL Types/Java Types Mapping
SQL Type Java Type

CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.Math.BigDecimal
DECIMAL java.Math.BigDecimal
BIT boolean
TINYINT int
SMALLINT int
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
try { Display the records based on the user input
Connection con=null;
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee1","root","");
System.out.println("Connection Succesfull");
Statement s=con.createStatement(); // insert a record into table
catch(SQLException e)
Scanner inp=new Scanner(System.in); {
System.out.println("Enter the Name: "); System.out.println(e.getMessage());
String name=inp.next(); }
String sql="select * from empinfo where empname=?;"; }
//to scroll the cursor back and forth
PreparedStatement ps=con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ps.setString(1,name);
ResultSet rs=ps.executeQuery();
if(rs.next()==false){
System.out.println("Record not found"); }
else{
rs.previous();
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getBigDecimal(2)+" "+rs.getDate(3)+" "+rs.getInt(4)); }
}
ps.close();
con.close();
}
Example : Connecting Javafx with Database
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.*; Demo of connecting Javafx
import javafx.scene.layout.*;
import javafx.event.*; with Database
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
class Employee
{
private String name;
private String password;
public Employee(String name, String password)
{
this.name = name;
this.password = password;
}
public void insertstudent() throws SQLException,ClassNotFoundException,InstantiationException, IllegalAccessException
{
Connection con=null;//Establish a connection
Class.forName("com.mysql.jdbc.Driver").newInstance();//loads the driver
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cse1007","root","");
String sql="insert into login values(?,?);";
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setString(1,name);
stmt.setString(2,password);
stmt.execute();
}
}
bSubmit.setOnAction(new EventHandler<ActionEvent>()
class MyloginForm
{
{
@Override
Label lname; Demo of connecting Javafx public void handle(ActionEvent event)
TextField tname; with Database {
Label lpwd;
boolean flag=true;
//TextField tpwd;
if(tpwd.getText().isEmpty())
PasswordField tpwd;
{
Button bSubmit;
lerrormsg.setText("Enter your name");
Label lerrormsg;
flag=false;
public void myform(Stage primaryStage)
}
{
if(tname.getText().isEmpty())
lname=new Label("Enter your name");
{
tname=new TextField();
lerrormsg.setText("Enter your pssword");
lpwd=new Label ("Ener your password");
flag=false;
tpwd=new PasswordField();
}
lerrormsg=new Label();
Employee e=new Employee(tname.getText(),tpwd.getText());
bSubmit=new Button("Submit");
try
GridPane root=new GridPane();
{
root.add(lname,0,0);
e.insertstudent();
root.add(lpwd,0,2);
if(flag)
root.add(tname,1,0);
lerrormsg.setText("Record inserted Successfully");
root.add(tpwd,1,2);
else
root.add(bSubmit,0,3);
lerrormsg.setText("Record Not inserted Successfully");
root.add(lerrormsg,0,4);
}
Scene sc=new Scene(root,500,300);
catch (Exception ex)
primaryStage.setScene(sc);
{
primaryStage.show();
System.out.println(ex.getMessage());
}
}
});
}}
Demo of connecting Javafx with Database

public class samplemysql4 extends Application


{
@Override
public void start(Stage primaryStage) throws Exception
{
MyloginForm login=new MyloginForm();
login.myform(primaryStage);
}
public static void main(String[] args)
{
launch(args);
}

}
Demo of connecting
Javafx with Database

OUTPUT
import java.sql.*;
import java.sql.Driver;
Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class samplemysql2


{
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
IllegalAccessException
{
try
{
Connection con=null;//Establish a connection
Class.forName("com.mysql.jdbc.Driver").newInstance();//loads the driver
//define the connection propertiesi.e dbname, username and password
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cse1007","root","");
System.out.println("Connection Successful");
Statement s1=con.createStatement(); // insert a record into table
//Execute the Query
//s1.executeUpdate("update slotc1 set dept='CSE' where rno=100;");
//System.out.println("Record Updated");
s1.executeUpdate("INSERT INTO slotc1 VALUES(99,'san','cse',5650);");
System.out.println("Record Inserted");
ResultSet rs=s1.executeQuery("select * from slotc1;");
Example
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4));
}
s1.close();
con.close();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}

You might also like