0% found this document useful (0 votes)
7 views8 pages

Unit 8 2

The document discusses Java Database Connectivity (JDBC) and how to connect and execute SQL queries against databases from Java applications. It covers database basics, the Structured Query Language (SQL) and basic SQL operations like creating tables, inserting, updating, retrieving, and deleting records. It also provides examples of establishing a JDBC connection and executing queries.

Uploaded by

kafle1292
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

Unit 8 2

The document discusses Java Database Connectivity (JDBC) and how to connect and execute SQL queries against databases from Java applications. It covers database basics, the Structured Query Language (SQL) and basic SQL operations like creating tables, inserting, updating, retrieving, and deleting records. It also provides examples of establishing a JDBC connection and executing queries.

Uploaded by

kafle1292
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

Unit 8: JDBC
What is JDBC?
 JDBC stands for Java Database Connectivity which is a technology that allows Java
applications to interact with relational databases and execute SQL queries against the
databases.
 JDBC is a java API to connect and execute query with the database.
 JDBC API uses jdbc drivers to connect with the database.
Database Basics
A database as the name suggests is a sophisticated system for storing the data. Databases store the
data in the form of tables with each table containing several records of data. Databases are broadly
categorized into two types as listed below:
 Single table databases and
 Multi table or relational databases.
A single table databases doesn’t mean that they have just one table. It will have several tables of
data and all the tables are independent of each other. The main drawback with these databases is
the lack of flexibility while retrieving the data.
On the other hand in multi table databases, two or more tables are related with other. This feature
offers more flexibility and power to retrieve the data. These databases are therefore called as
relational databases. Most of the modern enterprises use relational databases
Structured Query Language (SQL)
Structured Query Language which is abbreviated as SQL is a standard query language for working
with relational databases. SQL is Structured Query Language, which is a computer language for
storing, manipulating and retrieving data stored in a relational database. SQL is the standard
language for Relational Database System. All the Relational Database Management Systems
(RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL
as their standard database language. SQL is required:
To create new databases, tables and views
 To insert records in a database
 To update records in a database
 To delete records from a database
 To retrieve data from a database

Compiled By: Tara Bahadur Thapa pg. 1


Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

Creating a table
The SQL syntax for creating a table is shown below:
CREATE TABLE ( COLUMN 1 NAME COLUMN 1 TYPE, COLUMN 2 NAME COLUMN 2 TYPE,
. . COLUMN N NAME COLUMN N TYPE );
Using the above syntax, to create the customers table, the SQL query will be as shown bellow:
CREATE TABLE Customers ( FirstName VARCHAR(50), LastName VARCHAR (50), SSN
NUMERIC(10), Age NUMERIC(10), City VARCHAR (32), State VARCHAR (2), Country
VARCHAR (32) )
Inserting the data into the table
To insert the data into the tables, we use the INSERT query. A single insert query inserts one
record or row of data. Following is the sql syntax.
INSERT INTO VALUES (COL1 DATA, COL2 DATA …. COL (N) DATA);
Using the above syntax, we insert the record into customers table as
INSERT INTO Customers VALUES (‘Smith’, ‘John’, 123456, 20, ‘Vegas’, ‘CA’, ‘USA’);
You can specify or ignore the column names while using INSERT INTO statement. To insert
partial column values, you must have to specify the column names. But if you want to insert all
the column values, you can specify or ignore the column names.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1,
value2, value3,...valueN);
Updating records in table
To update the data in an existing record, we use the UPDATE query statement. The syntax for this
query is shown below:
UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE
[condition];
Example:
UPDATE CUSTOMERS SET FirstName = ‘Joe’, LastName = ‘Roberts’ WHERE SSN = 123456
Retrieving records from table
Retrieving the records is the most important database operation. We use the SELECT query to
retrieve the records. The syntax for this query is as shown below:
SELECT COL 1 NAME, COL2 NAME …… FROM

Compiled By: Tara Bahadur Thapa pg. 2


Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

WHERE
If the query has no WHERE clause, then it retrieves the selected columns from all the records in
the table. Based on this, let’s see few cases here:
Case 1: Retrieve all the customers data
SELECT * from Customers; In the above sql asterisk(*) means all columns of data. Since there is
no WHERE clause in the query, it will pull up all the records. The result of the above query is the
entire table.
Case 2: Select all the customers who belong to the state of CA.
SELECT * FROM Customers WHERE State = ‘CA’; The above query will retrieve those records
whose state is CA
Case 3: Retrieve the first names and last names whose country is USA and state is CA
(multiple conditions)
SELECT firstName, lastName from Customers WHERE State=’CA’ AND Country=’USA’;
Deleting the records
To delete the records in the table we use DELETE query. The syntax for this query is shown below:
DELETE FROM WHERE
For instance, to delete all the customers whose state is CA, the query will be,
DELETE FROM Customers where State=’CA’;
These are all the basic SQL operations you need to know to work with any database

JDBC Connection Steps


#1) Import Packages
import java.sql.*;
#2) Load Driver
We should load/register the driver in the program before connecting to the Database. You need to
register it only once per database in the program.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Class.forName()

Compiled By: Tara Bahadur Thapa pg. 3


Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

#3) Establish Connection


The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String passwrd)
throws SQLException
#4) Create And Execute Statement
The createStatement() method of Connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Syntax of createStatement() method public Statement createStatement()throws SQLException
Example to create the statement object Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method public ResultSet executeQuery(String sql)throws
SQLException
By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection. Syntax of close()
method public void close()throws SQLException

Compiled By: Tara Bahadur Thapa pg. 4


Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

Example
import java.sql.*;
public class dataBaseTest
{
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL ="jdbc:mysql://localhost/login";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";

void connectDBAndInsert()
{
try
{
Class.forName(DRIVER_NAME);
Connection con;
con= DriverManager.getConnection(DB_URL, DB_USERNAME,DB_PASSWORD);
String myQuery = "INSERT INTO user VALUES(?,?)";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setString(1,"Abhi");
pstmt.setInt(2,27);
pstmt.executeUpdate();
System.out.println(" Record is added. Thank you");
pstmt.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}

Compiled By: Tara Bahadur Thapa pg. 5


Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

void delete()
{
try
{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,DB_PASSWORD);
String myQuery = "DELETE FROM user WHERE pass =?";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1,27);
pstmt.executeUpdate();
System.out.println(" Record is deleted. Thank you");
pstmt.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
void display()
{
try
{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,DB_PASSWORD);
String myQuery = "SELECT * from user where name=?";

Compiled By: Tara Bahadur Thapa pg. 6


Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

//String myQuery = "SELECT * from user";


PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setString(1,"Tara");
ResultSet rs;
rs = pstmt.executeQuery();
while(rs.next())
{
String uname=rs.getString("name");
int upass=rs.getInt("pass");
System.out.println("User name="+uname);
System.out.println("User Password="+upass);
}
pstmt.close();
con.close();
}
catch(Exception e)
{

}
}
public static void main(String args[])
{
dataBaseTest d=new dataBaseTest();
//d.connectDBAndInsert();
// d.delete();
d.display();
}
}
TU Exam Questions Solution
2016- Q.no. 6

Compiled By: Tara Bahadur Thapa pg. 7


Unit 8: JDBC Java Programming II BIM 5TH SEMESTER

import java.sql.*;
public class TUExam2016 {

Connection con;
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL ="jdbc:mysql://localhost/login";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
public void connect() throws Exception
{
Class.forName(DRIVER_NAME);
con=DriverManager.getConnection(DB_URL,DB_USERNAME,DB_PASSWORD);
if(con!=null)
{
System.out.println("Successfully connected to database");
}
else
{
System.out.println("Error connecting to database!");
}
}
public static void main(String[] args) throws Exception
{
TUExam2016 t=new TUExam2016();
t.connect();
}
}

Compiled By: Tara Bahadur Thapa pg. 8

You might also like