JDBC
JDBC
Introduction to JDBC
□JDBC is used for accessing databases from
Java applications
□Information is transferred from relations to objects
and vice-versa
databases optimized for searching/indexing
objects optimized for engineering/flexibility
7
JDBC Architecture
Oracle
Driver
Oracle
DB2
Network
MySQL
Driver
We will
use this one… MySQL
8
JDBC Architecture (cont.)
Application JDBC Driver
12
Connecting to the Database
• Every database is identified by a URL
• Given a URL, DriverManager looks for the
driver that can talk to the corresponding
database
• DriverManager tries all registered drivers, until
a suitable one is found
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection("jdbc:mysql://
localhost:3306/databasename","root","");
13
Interaction with the Database
• We use Statement objects in order to
– Query the database
– Update the database
• Three different interfaces are used:
Statement, PreparedStatement,
CallableStatement
• All are interfaces, hence cannot be instantiated
• They are created by the Connection
prepareStatement("SELECT * FROM patient");
You have to import all library classes required for the project
like
import java.sql.*;
Querying with Statement
String queryStr =
"SELECT * FROM employee
" + "WHERE lname =
‘Ahmed'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(queryStr);
15
Changing DB with Statement
String deleteStr =
"DELETE FROM employee "
+ "WHERE lname =
‘Ahmed'";
Statement stmt = con.createStatement();
int delnum = stmt.executeUpdate(deleteStr);
• executeUpdate is used for data manipulation: insert, delete, update, create table,
etc. (anything other than querying!)
• executeUpdate returns the number of rows modified
16
inserting data into MYSQL table
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:m
ysql://localhost:3306/dbname","root","");
prepareStatement("INSERT INTO patient
VALUES(?,?,?,?,?,?,?)");
Inserting data from Jform
import java.sql.*;
Connection conn=null;
PreparedStatement st=null;
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/
dbname","root","");
st=conn.prepareStatement("INSERT INTO patient
VALUES(?,?,?,?,?,?,?)");
st.setString(1,fname.getText());
st.setString(2,lname.getText());
st.setString(3,email.getText());
st.setString(4,city.getText());
st.setString(5,phone.getText());
st.setString(6,dep.getText());
st.executeUpdate();