Ebook QA QE 1 L3 Creating Database Using JDBC Final
Ebook QA QE 1 L3 Creating Database Using JDBC Final
Course(s):
Fundamentals of SQL
▪ Explain what are relational databases
- What are databases?
- Tables and relations
▪ Join tables
- Inner joins, outer joins, and self joins
▪ Manipulate data
- Insert statement
- Update statement
- Delete statement
A Day in the Life of a Test Engineer
To make the user experience better, Joe must write a program where
the particular product details are fetched from the database and
displayed on the dashboard after the user enters the product ID.
Explain JDBC
Java Application
JDBC API
Database
JDBC Driver and Types
A JDBC driver is a software component that enables a Java application to interact with a
database.
Native-API Driver
Types
Network-Protocol Driver
Thin Driver
JDBC API
A JDBC API provides data access from the Java programming language. JDBC API includes
java.sql and javax.sql packages. JDBC API is implemented through a JDBC driver.
Databases
DataSource Establishes connections
Statement,
PreparedStatement, and Execute SQL queries
CallableStatement
1 Register driver
2 Get connection
3 Create statement
4 Execute query
5 Close connection
Set up a JDBC Environment
Duration: 25 min.
Problem Statement:
Set up a JDBC environment.
Assisted Practice: Guidelines
Duration: 25 min.
Problem Statement:
Set up a JDBC environment.
Unassisted Practice: Guidelines
3. Create a servlet that creates a JDBC connection to the database and closes it.
Statement Interfaces:
The Statement object uses the execute method to execute the SQL query.
Execute
int execute (String SQL) ResultSet executeQuery (String SQL)
methods
Data read by SQL statements are returned in a result set. Result set of a database query is
represented by the ResultSet interface.
Navigational
methods Move the cursor to the next row
ResultSet Concurrency
Concurrency Description
Based on cursor manipulation and concurrent changes to the underlying data source, a
ResultSet object can be classified into three types: TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE.
The cursor can scroll forward Sensitive to database changes that occur
TYPE_SCROLL_SENSITIVE and backward after the creation of the result set
JDBC Connections, Statements, and ResultSet
Duration: 45 min.
Problem Statement:
Demonstrate Connection, Statement, and ResultSet in JDBC.
Assisted Practice: Guidelines
2. Create a dynamic web project to connect to the database and perform data operations via JDBC.
A stored procedure is a prepared SQL code that can be saved and reused. It can contain more
than one SQL statement.
Depending on the transactions in which the stored procedures are invoked, they are classified
as non-nested connections and nested connections.
Prepare a callable
statement 1
Register the output parameters
2 (if any)
SQLException Methods:
Method Description
getErrorCode() Returns the error number
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the specified print stream
printStackTrace(PrintWriter w) Prints this throwable and its backtrace to the specified print writer
printStackTrace( ) Prints the throwable and its backtrace or the current exception to a
standard error stream
Stored Procedures and Exception Handling
Duration: 40 min.
Problem Statement:
Demonstrate stored procedures and exception handling in JDBC.
Assisted Practice: Guidelines
2. Create a dynamic web project to connect to the database and execute a stored procedure.
Before creating, selecting, and updating a database using JDBC, check if:
Close
Import JDBC Open a
database
packages connection
resources
1 2 3 4 5
Import JDBC
1
packages Sample Code
Import JDBC
1
packages
3 Open a connection
Class.forName("com.mysql.jdbc.Driver");
Close database
5
resources
Create a Database
Import JDBC
1
packages
3 Open a connection
Connection connect =
DriverManager.getConnection(database_URL,
4 Execute the query userName, password);
Close database
5
resources
Create a Database
Import JDBC
1
packages
3 Open a connection
Statement stmt = connect.createStatement();
String sqlString = “CREATE DATABASE SAMPLE”;
4 Execute the query stmt.executeUpdate(sqlString);
Close database
5
resources
Create a Database
Import JDBC
1
packages
3 Open a connection
stmt.close(); connect.close();
4 Execute the query
Close database
5
resources
Steps to Select a Database
Import JDBC
1
packages
The name of the database to be selected must be
Register the JDBC mentioned in the database URL
2
driver
Close
Import JDBC Open a
database
packages connection
resources
1 2 3 4 5
The name of the database to be dropped must be mentioned in the database URL.
Sample Code
Duration: 45 min.
Problem Statement:
Demonstrate how to create, select, and drop a database in JDBC.
Assisted Practice: Guidelines
1. Create a dynamic web project to use JDBC to create, select, and drop a database.
Duration: 45 min.
Problem Statement:
Demonstrate how to create, select, and drop a database in JDBC.
Unassisted Practice: Guidelines
1. Create a dynamic web project to use JDBC to create, select, and drop a database.
Insert a record in the table, update an existing record, or delete a record in the table by
following the steps below:
Example
// Database to be connected to
static final String database_URL =
"jdbc:mysql://localhost/databaseName";
Example
// Database to be connected to
static final String database_URL =
"jdbc:mysql://localhost/databaseName";
A DELETE statement is used to delete an existing record from the database table.
Example
// Database to be connected to
static final String database_URL =
"jdbc:mysql://localhost/databaseName";
Duration: 45 min.
Problem Statement:
Demonstrate database record handling using JDBC.
Assisted Practice: Guidelines
7. Create a ProductDetails servlet to add, update, and delete records from the table.
▪ The ACID (Atomicity, Consistency, Isolation and Durability) properties describe transaction management.
o Consistency ensures that the database is brought from one consistent state to another consistent state.
o Isolation ensures that each transaction is isolated from the other transaction.
o Durability means that once a transaction has been committed, it will remain so, even in the event of
errors or power loss.
Transaction Management: JDBC
Statement: It is used for general-purpose access to your database. It is useful when you are using
static SQL statements at runtime. The Statement interface cannot accept parameters.
Syntax:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String sets the String value to the given parameter index.
value)
public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)
public int executeUpdate() executes the query. It is used to create, drop, insert,
update, delete, etc.
public ResultSet executeQuery() executes the select query. It returns an instance of
ResultSet.
Transaction Management: JDBC
Example: PreparedStatement:
import java.sql.*;
class FetchRecords
{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:x
e","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
Transaction Management: JDBC
Example: Transaction Management in JDBC using PreparedStatement
import java.sql.*;
import java.io.*;
class TM
{
public static void main(String args[]){
try{
class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
System.out.println("enter salary");
String s3=br.readLine();
Transaction Management: JDBC
Transaction Management in JDBC using PreparedStatement
int salary=Integer.parseInt(s3);
ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit(); }
if(answer.equals("rollback")){
con.rollback(); }
System.out.println("Want to add more records y/n");
String ans=br.readLine();
if(ans.equals("n")){
break;
}}
con.commit();
System.out.println("record successfully saved");
con.close();//before closing connection commit() is called
}catch(Exception e){System.out.println(e);} }}
Transaction Management: JDBC
Once you have created a function in the database, call that function:
import java.sql.*;
public class FuncSum {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");
stmt.setInt(2,10);
stmt.setInt(3,43);
stmt.registerOutParameter(1,Types.INTEGER);
stmt.execute();
System.out.println(stmt.getInt(1));
}
}
Transaction Management
Duration: 30 min.
Problem Statement:
Demonstrate Transaction Management in JDBC.
Assisted Practice: Guidelines
Duration: 45 min.