Unit 8 2
Unit 8 2
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
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
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
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);
}
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=?";
}
}
public static void main(String args[])
{
dataBaseTest d=new dataBaseTest();
//d.connectDBAndInsert();
// d.delete();
d.display();
}
}
TU Exam Questions Solution
2016- Q.no. 6
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();
}
}