SlideShare una empresa de Scribd logo
1 de 7
Descargar para leer sin conexión
JDBC - 1

JDBC
THE JAVA.SQL PACKAGE:
The java.sql package contains many classes and interfaces that are used by the JDBC API.
These classes and interfaces enable the following basic database functions: creating, opening and
managing connections to a database, executing SQL statements, processing the results in the
ResultSet, and closing the connection.
Some of the Classes and Interfaces of java.sql package are explained below:
1. The DriverManager
This class works as an interface between the application (UI) and the Microsoft Access database.
It provides the methods for managing database drivers.
getConnection(jdbc:odbc:name of DSN, <username>, <password>)
This method attempts to establish a connection to the specified database by invoking the
JDBC:ODBC bridge and by accepting the name of the DNS as an argument. The system DSN
knows where the Access database is.
Once a physical connection with a database has been established, we initialize the SQL queries
that will be used on the database.
ResultSet: The data records retrieved from the database table are held in ResultSet object. Once
the table is held in the ResultSet object, the records and the individual fields of each record can be
manipulated.
The ResultSet contains zero, one or many records. Since this object is created in memory, its
contents cannot be seen. To see the data held within the ResultSet object, its each row must be
read. We can read each record by using a while loop. The rs.next() method is used in a loop to
get one row at a time from the table.

2. Connection Interface:
A Connection object represents a connection with a database. SQL statements can be executed
and ResultSets are returned from the table.
Methods used from Connection interface:
a) void close(); The close() method will release the database resources and JDBC
resources.
b) Statement createStatement(); This method returns a new object that can be used
to execute SQL statements.
c) void close() - immediately closes the current connection and the JDBC resources it
created.
Prof. Mukesh N. Tekwani

Page 1 of 7
JDBC
3. Statement Interface:
A Statement object executes statements and obtains results after their execution. The results are in
the form of ResultSet object.
Methods used from Statement interface:
a) ResultSet executeQuery(String sqlstmt) - This method executes a SQL
query that returns a single ResultSet object.
b) int executeUpdate(String sqlstmt) - This method executes the SQL UPDATE,
DELETE or INSERT statements. It also executes the DDl statements such as CREATE
TABLE. It returns a row count or -1 for a statement without an update count.
c) int getUpdateCount – It returns the number of rows affected by the previous update
statement or -1 if the preceding statement did not have an update count.
d) boolean isClosed() – returns true if this statement is closed.

4. PreparedStatement Interface:
This interface extends the Statement interface. If a particular SQL statement has to be executed
many times, it is precompiled and stored in a PreparedStatement object. This object is then
used many times to execute the statement.
Methods used from PreparedStatement interface:
a) executeQuery() - This method executes prepared SQL query and returns a ResultSet
object..
b) executeUpdate() - This method executes the prepared SQL UPDATE, DELETE or
INSERT statements. It returns the number of rows affected. For DDL statements such as
CREATE TABLE, it returns a 0.
c) void setXxx(int n, Xxx x)– sets the value of the nth parameter to x. Xxx is data type.
d) void clearParameters() – clears all current parameters in the prepared statement.
Example: Consider a query for all books by a publisher, independent of the author. The SQL
query is:
SELECT Books.Price, Books.Title
FROM Books, Publishers
WHERE Books.Publisher_Id = Publishers.Publisher_Id
AND Publishers.Name = the name from the list box
Instead of building a separate query each time the user gives this query, we can prepare a query
with a host variable and use it many times, each time filling in a different string for the variable.
We can prepare this query as follows:
String publisherQuery =
“SELECT Books.Price, Books.Title” +
“ FROM Books, Publishers” +
“ WHERE Books.Publisher_Id = Publishers.Publisher_Id
AND Publishers.Name = ?”;
Page 2 of 7

mukeshtekwani@hotmail.com
JDBC - 1
PreparedStatement publisherQueryStat =
conn.prepareStatement(publisherQuery);
Before executing the prepared statement, we must bind the host variables to actual values with a
set method. There are different set methods for different data types. To set a string to a publisher
name:
publisherQueryStat.setString(1, publisher)
The first argument is the position number of the host variable that we want to set. The position 1
denotes the first ?. The second argument is the value we want to assign to the host variable.
Once the variables have been bound to values, we can execute the query:
ResultSet rs = publisherQueryStat.executeQuery()

5. ResultSet Interface:
The data generated by the execution of a SQL statement is stored in a ResultSet object.This
object can access only one row at a time. This row is called as its current row. When the SQL
statement is re-executed, the current recordset is closed and a new RecordSet object is created.
Methods used from ResultSet interface:
a) void close()- This method is used to release a ResutSet.
b) void getString()- This method is used to get the value of a column in the current row.
c) next() – A ResultSet is initially positioned before its first row. The first time we call the
next() method, it makes the first row as the current row. The second time we call the next()
method, the second row becomes the current row, etc
d) getXxx(int col no) and getXxx(String collabel) - it returns the value of a
column with the given column number or label, converted to the specified type. Here Xxx is a
data type such as int, double, String, Date, etc.
e) int findColumn(String colname) – gives the column index associated with a
column name.
f) boolean isClosed() – returns true if this statement is closed.
g) boolean first() and boolean last() – moves the cursor to the first or last row.
Returns true if the cursor is positioned on a row.
h) boolean isFirst() and boolean isLast()– Returns true if the cursor is positioned
on first row or last row.

6. ResultSetMetaData Interface:
This object is returned by the getMetaData() constructor. It gives information about number of
columns, their types and properties or in general about the structure of a database.
Methods used from ResultSet interface:
a) getColumnCount()- This method returns the number of columns in the ResutSet.
b) String getColumnName(int) – This method returns the name of a specific column.
c) getTableName() – This method returns the name of a table.
Prof. Mukesh N. Tekwani

Page 3 of 7
JDBC
d) DataBaseMetaData metadt = conn.getMetaData();

DATA SOURCE NAME (DSN)
If the original database is created in, say Microsoft Access, then we create a DSN. DSN stands
for Data Source Name. A DSN is itself a data structure that contains information about the
database, such as, the driver type, the database name, the actual location of the database on the
hard disk (i.e., the path), the user name and a password.
All this information in DSN is required by ODBC to drivers for creating a connection to the
database. DSN is used from an application to send or receive data to the database. DSN is stored
in the system registry.

GETTING DATA FROM COLUMNS OF A TABLE (ACCESSORS):
1. There are various accessors that permit us to read the contents of a field.
2. Each accessor has two forms, one takes a numeric argument and the other takes a string
argument.
3. When we give supply a numeric argument we are referring to the column with that number.
E.g., rs.getInt(1)returns the value of the first column.
4. When we supply a string argument we refer to the column in the result set with that
name.E.g., rs.getInt("Rollno") returns the value of the column with the name
RollNo.
5. The following are the getXXX() methods available to get the column data from the current
row:
String
boolean
int
float
byte
double
long

getString(String columnname);
getBoolean (String columnname);
getint(String columnname);
getfloat(String columnname);
getByte(String columnname);
getDouble(String columnname);
getLong(String columnname);

ACCESSING COLUMNS BY COLUMN INDEXES
Program : This program demonstrates how we can use the column indexes to identify the
columns of the current row.
stmt = conn.createStatement( );

ResultSet
rs = stmt.executeQuery(“SELECT RollNo, Name, Marks1
FROM TYBSc”);
while (rs.next())
{
int r = rs.getInt(1);
String n
= rs.getString(2);
Page 4 of 7

mukeshtekwani@hotmail.com
JDBC - 1
int m1 = rs.getInt(3);
System.out.print(r + "t");
System.out.print(n + "tt");
System.out.print(m1 + "tt");
}

TRANSACTIONS
1. A group of statements form a transaction.
2. A transaction can be committed if all the statements in the group are executed successfully. If
one statement in the group fails, the transaction can be rolled back as if none of the statements
has been issued.
3. Why should we group statements into a transaction? This is done for maintaining database
integrity. E.g., in a banking environment, if money is transferred from one account to another,
we must debit one account and simultaneously credit another account. If any one of these
transactions cannot be executed the other should also not be executed. Thus, if a debit has
taken place but the credit cannot take place, the debit statement should also be disallowed.
4. When statements are grouped in a transaction, then the transaction either succeeds in full and
it can be committed or it fails somewhere and the transaction can be rolled back (like undo
feature). This rollback will cancel all the updates to the database.
5. By default, a database connection is in autocommit mode. That is each SQL statement is
committed to the database as soon as it is executed. Once a statement is committed, you
cannot roll it back. We can turn off this default option as follows:
conn.setAutoCommit(false)
6. Example:
a. Create a Statement object as usual:
Statement stat = conn.createStatement();
b. Call executeUpdate() any number of times, as follows:
stat.executeUpdate(command1);
stat.executeUpdate(command2);
stat.executeUpdate(command3);
:
:
c. If all statements have been executed successfully, call the commit method() as
foolows:
conn.commit();
d. But if any error has occurred, we can call the rollback() command as follws:
conn.rollback();
Save Points:
We can control the position upto which we want to rollback the commands. This is done by using
save points. By creating a save point, we are marking points upto which we can later return
without abandoning the entire transaction.
Statement stat = conn.createStatement(); //start transaction; rollback goes here
Prof. Mukesh N. Tekwani

Page 5 of 7
JDBC
stat.executeUpdate(command1);
Savepoint svpt = conn.setSavePoint(); // set save point, rollback(svpt) will go here
stat.executeUpdate(command2);
if ( . . . ) conn.rollback(svp);
. . .
conn.commit();

//undo effect of command 2

If a savepoint is no longer needed, we must release it as follows:
conn.releaseSavepoint(svpt);

PROGRAMMING EXERCISES
1. Write a JDBC program to create a table GRTGS (Message – Text), insert two greetings into the table,
display the table contents, and drop the table. Assume the DSN name is GREETINGS.
2. Use JDBC API to do the following:
• Create a table in Oracle with following structure.
FriendName
Text(20)
Dob
Date
Details
Text(20)
PhoneNumber
Number
• Insert the records
• Show all the records from the table.
3. Write a program that takes values for BookName and BookId from the user on command prompt and
inserts the values in the table Book assuming table to be already created.
4. Write a program that retrieves the records from Book having field Book ,BookName and BookId
5. Write a program that searches for record in table BOOK(BookName varchar2(25),BID
number(2,5)) .The value for the BookName is taken from command prompt ,if record found “Record
Found” message is displayed and the details regarding the respective Book is displayed else “Record
Not Found” is displayed.
6. Write a JDBC program that accepts a table name and displays the total number of records in it.
7. Write a JDBC program that prints the names of all columns in a table that is given on the command
line.
8. Write a JDBC program to change the name of a column. Table name is supplied on command line.
9. Create a database “EMPLOYEEDB.MDB” through Microsoft Access. Create a Data Source Name
(DSN); give an appropriate name for DSN. Then write a single program to create a table EMPLOYEE
(ENO – Integer, ENAME-Text, BPAY-double, ALLOWANCES-double, TAX-double, NETPAYdouble). Through the same program insert 5 records, and display the output in a tabular manner.
NETPAY must be calculated and entered in the table using the formula: NETPAY = BPAY +
ALLOWANCES – TAX.
10. Write a program that accepts an employee number (ENO) for the above database and if it is found in
the table, prints its details, else prints “Record not found”.
11. Modify (alter) the above table (EMPLOYEE) so that it contains one more column called
DESIGNATION. Give appropriate SQL query to update this column. Then display all records where
designation is “Manager”.

Page 6 of 7

mukeshtekwani@hotmail.com
JDBC - 1

REVIEW QUESTIONS
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

16.

What are the components of JDBC?
Explain the three statement objects in JDBC
Explain types of execute methods in JDBC with examples.
Explain DriverManager class and its methods.
What is DSN? How is it created?
Explain steps for connectivity in JDBC
Explain any 4 methods of PreparedStatement.
Discuss the two-tier architecture for data access.
Discuss the three-tier architecture for data access. What are its advantages over the two-tier
architecture?
Differentiate between Statement and PreparedStatement
Explain different methods of ResultSet object.
State the object which encapsulates the data retrieved from the database. State the method which is
used to to get the value of the specified column of the current row from a database.
State the method which is used to get the value of the specified column of the current row from a
database.
Which method is used to execute a SELECT query? Which method is used to execute DDL statements
such as INSERT, UPDATE, and DELETE?
Write short notes on:
a. JDBC
b. JDBC-ODBC Bridge
c. Types of driver managers in JDBC
d. PreparedStatement
e. Transaction and savepoint
Explain the following method, and also state the class/interface to which they belong:
• next()
• close()
• forName()
• createStatement()
• executeUpdate()
• prepareStatement()
• getConnection()
• getString()
• getColumnCount()

Prof. Mukesh N. Tekwani

Page 7 of 7

Más contenido relacionado

La actualidad más candente

Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Ameer B. Alaasam
 
0php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-30php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-3Fafah Ranaivo
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207Jay Coskey
 
Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocolWoodruff Solutions LLC
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn Sagar Arlekar
 
Object and class in java
Object and class in javaObject and class in java
Object and class in javaUmamaheshwariv1
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 
Java script introducation & basics
Java script introducation & basicsJava script introducation & basics
Java script introducation & basicsH K
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R LanguageGaurang Dobariya
 

La actualidad más candente (20)

Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
03 structures
03 structures03 structures
03 structures
 
Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016)
 
0php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-30php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-3
 
Array
ArrayArray
Array
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207
 
Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocol
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
PostgreSQL Modules Tutorial - chkpass, hstore, fuzzystrmach, isn
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Java unit2
Java unit2Java unit2
Java unit2
 
SQL
SQLSQL
SQL
 
Object and class in java
Object and class in javaObject and class in java
Object and class in java
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Java script introducation & basics
Java script introducation & basicsJava script introducation & basics
Java script introducation & basics
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R Language
 

Destacado

Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingMukesh Tekwani
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular ExpressionsMukesh Tekwani
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsMukesh Tekwani
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQMukesh Tekwani
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing filesMukesh Tekwani
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signalsMukesh Tekwani
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1Mukesh Tekwani
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferWayne Jones Jnr
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programmingMukesh Tekwani
 

Destacado (18)

Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Html tables examples
Html tables   examplesHtml tables   examples
Html tables examples
 
Html graphics
Html graphicsHtml graphics
Html graphics
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQ
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Data Link Layer
Data Link Layer Data Link Layer
Data Link Layer
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signals
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programming
 

Similar a Java 1-contd (20)

Java Databse Connectvity- Alex Jose
Java Databse Connectvity- Alex JoseJava Databse Connectvity- Alex Jose
Java Databse Connectvity- Alex Jose
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
JDBC JAVA DATABASE CONNECTIVITY AND JAVA
JDBC JAVA DATABASE CONNECTIVITY AND JAVAJDBC JAVA DATABASE CONNECTIVITY AND JAVA
JDBC JAVA DATABASE CONNECTIVITY AND JAVA
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatable
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatable
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
JDBC
JDBCJDBC
JDBC
 
Lecture17
Lecture17Lecture17
Lecture17
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 

Más de Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

Más de Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Último (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Java 1-contd

  • 1. JDBC - 1 JDBC THE JAVA.SQL PACKAGE: The java.sql package contains many classes and interfaces that are used by the JDBC API. These classes and interfaces enable the following basic database functions: creating, opening and managing connections to a database, executing SQL statements, processing the results in the ResultSet, and closing the connection. Some of the Classes and Interfaces of java.sql package are explained below: 1. The DriverManager This class works as an interface between the application (UI) and the Microsoft Access database. It provides the methods for managing database drivers. getConnection(jdbc:odbc:name of DSN, <username>, <password>) This method attempts to establish a connection to the specified database by invoking the JDBC:ODBC bridge and by accepting the name of the DNS as an argument. The system DSN knows where the Access database is. Once a physical connection with a database has been established, we initialize the SQL queries that will be used on the database. ResultSet: The data records retrieved from the database table are held in ResultSet object. Once the table is held in the ResultSet object, the records and the individual fields of each record can be manipulated. The ResultSet contains zero, one or many records. Since this object is created in memory, its contents cannot be seen. To see the data held within the ResultSet object, its each row must be read. We can read each record by using a while loop. The rs.next() method is used in a loop to get one row at a time from the table. 2. Connection Interface: A Connection object represents a connection with a database. SQL statements can be executed and ResultSets are returned from the table. Methods used from Connection interface: a) void close(); The close() method will release the database resources and JDBC resources. b) Statement createStatement(); This method returns a new object that can be used to execute SQL statements. c) void close() - immediately closes the current connection and the JDBC resources it created. Prof. Mukesh N. Tekwani Page 1 of 7
  • 2. JDBC 3. Statement Interface: A Statement object executes statements and obtains results after their execution. The results are in the form of ResultSet object. Methods used from Statement interface: a) ResultSet executeQuery(String sqlstmt) - This method executes a SQL query that returns a single ResultSet object. b) int executeUpdate(String sqlstmt) - This method executes the SQL UPDATE, DELETE or INSERT statements. It also executes the DDl statements such as CREATE TABLE. It returns a row count or -1 for a statement without an update count. c) int getUpdateCount – It returns the number of rows affected by the previous update statement or -1 if the preceding statement did not have an update count. d) boolean isClosed() – returns true if this statement is closed. 4. PreparedStatement Interface: This interface extends the Statement interface. If a particular SQL statement has to be executed many times, it is precompiled and stored in a PreparedStatement object. This object is then used many times to execute the statement. Methods used from PreparedStatement interface: a) executeQuery() - This method executes prepared SQL query and returns a ResultSet object.. b) executeUpdate() - This method executes the prepared SQL UPDATE, DELETE or INSERT statements. It returns the number of rows affected. For DDL statements such as CREATE TABLE, it returns a 0. c) void setXxx(int n, Xxx x)– sets the value of the nth parameter to x. Xxx is data type. d) void clearParameters() – clears all current parameters in the prepared statement. Example: Consider a query for all books by a publisher, independent of the author. The SQL query is: SELECT Books.Price, Books.Title FROM Books, Publishers WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = the name from the list box Instead of building a separate query each time the user gives this query, we can prepare a query with a host variable and use it many times, each time filling in a different string for the variable. We can prepare this query as follows: String publisherQuery = “SELECT Books.Price, Books.Title” + “ FROM Books, Publishers” + “ WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = ?”; Page 2 of 7 mukeshtekwani@hotmail.com
  • 3. JDBC - 1 PreparedStatement publisherQueryStat = conn.prepareStatement(publisherQuery); Before executing the prepared statement, we must bind the host variables to actual values with a set method. There are different set methods for different data types. To set a string to a publisher name: publisherQueryStat.setString(1, publisher) The first argument is the position number of the host variable that we want to set. The position 1 denotes the first ?. The second argument is the value we want to assign to the host variable. Once the variables have been bound to values, we can execute the query: ResultSet rs = publisherQueryStat.executeQuery() 5. ResultSet Interface: The data generated by the execution of a SQL statement is stored in a ResultSet object.This object can access only one row at a time. This row is called as its current row. When the SQL statement is re-executed, the current recordset is closed and a new RecordSet object is created. Methods used from ResultSet interface: a) void close()- This method is used to release a ResutSet. b) void getString()- This method is used to get the value of a column in the current row. c) next() – A ResultSet is initially positioned before its first row. The first time we call the next() method, it makes the first row as the current row. The second time we call the next() method, the second row becomes the current row, etc d) getXxx(int col no) and getXxx(String collabel) - it returns the value of a column with the given column number or label, converted to the specified type. Here Xxx is a data type such as int, double, String, Date, etc. e) int findColumn(String colname) – gives the column index associated with a column name. f) boolean isClosed() – returns true if this statement is closed. g) boolean first() and boolean last() – moves the cursor to the first or last row. Returns true if the cursor is positioned on a row. h) boolean isFirst() and boolean isLast()– Returns true if the cursor is positioned on first row or last row. 6. ResultSetMetaData Interface: This object is returned by the getMetaData() constructor. It gives information about number of columns, their types and properties or in general about the structure of a database. Methods used from ResultSet interface: a) getColumnCount()- This method returns the number of columns in the ResutSet. b) String getColumnName(int) – This method returns the name of a specific column. c) getTableName() – This method returns the name of a table. Prof. Mukesh N. Tekwani Page 3 of 7
  • 4. JDBC d) DataBaseMetaData metadt = conn.getMetaData(); DATA SOURCE NAME (DSN) If the original database is created in, say Microsoft Access, then we create a DSN. DSN stands for Data Source Name. A DSN is itself a data structure that contains information about the database, such as, the driver type, the database name, the actual location of the database on the hard disk (i.e., the path), the user name and a password. All this information in DSN is required by ODBC to drivers for creating a connection to the database. DSN is used from an application to send or receive data to the database. DSN is stored in the system registry. GETTING DATA FROM COLUMNS OF A TABLE (ACCESSORS): 1. There are various accessors that permit us to read the contents of a field. 2. Each accessor has two forms, one takes a numeric argument and the other takes a string argument. 3. When we give supply a numeric argument we are referring to the column with that number. E.g., rs.getInt(1)returns the value of the first column. 4. When we supply a string argument we refer to the column in the result set with that name.E.g., rs.getInt("Rollno") returns the value of the column with the name RollNo. 5. The following are the getXXX() methods available to get the column data from the current row: String boolean int float byte double long getString(String columnname); getBoolean (String columnname); getint(String columnname); getfloat(String columnname); getByte(String columnname); getDouble(String columnname); getLong(String columnname); ACCESSING COLUMNS BY COLUMN INDEXES Program : This program demonstrates how we can use the column indexes to identify the columns of the current row. stmt = conn.createStatement( ); ResultSet rs = stmt.executeQuery(“SELECT RollNo, Name, Marks1 FROM TYBSc”); while (rs.next()) { int r = rs.getInt(1); String n = rs.getString(2); Page 4 of 7 mukeshtekwani@hotmail.com
  • 5. JDBC - 1 int m1 = rs.getInt(3); System.out.print(r + "t"); System.out.print(n + "tt"); System.out.print(m1 + "tt"); } TRANSACTIONS 1. A group of statements form a transaction. 2. A transaction can be committed if all the statements in the group are executed successfully. If one statement in the group fails, the transaction can be rolled back as if none of the statements has been issued. 3. Why should we group statements into a transaction? This is done for maintaining database integrity. E.g., in a banking environment, if money is transferred from one account to another, we must debit one account and simultaneously credit another account. If any one of these transactions cannot be executed the other should also not be executed. Thus, if a debit has taken place but the credit cannot take place, the debit statement should also be disallowed. 4. When statements are grouped in a transaction, then the transaction either succeeds in full and it can be committed or it fails somewhere and the transaction can be rolled back (like undo feature). This rollback will cancel all the updates to the database. 5. By default, a database connection is in autocommit mode. That is each SQL statement is committed to the database as soon as it is executed. Once a statement is committed, you cannot roll it back. We can turn off this default option as follows: conn.setAutoCommit(false) 6. Example: a. Create a Statement object as usual: Statement stat = conn.createStatement(); b. Call executeUpdate() any number of times, as follows: stat.executeUpdate(command1); stat.executeUpdate(command2); stat.executeUpdate(command3); : : c. If all statements have been executed successfully, call the commit method() as foolows: conn.commit(); d. But if any error has occurred, we can call the rollback() command as follws: conn.rollback(); Save Points: We can control the position upto which we want to rollback the commands. This is done by using save points. By creating a save point, we are marking points upto which we can later return without abandoning the entire transaction. Statement stat = conn.createStatement(); //start transaction; rollback goes here Prof. Mukesh N. Tekwani Page 5 of 7
  • 6. JDBC stat.executeUpdate(command1); Savepoint svpt = conn.setSavePoint(); // set save point, rollback(svpt) will go here stat.executeUpdate(command2); if ( . . . ) conn.rollback(svp); . . . conn.commit(); //undo effect of command 2 If a savepoint is no longer needed, we must release it as follows: conn.releaseSavepoint(svpt); PROGRAMMING EXERCISES 1. Write a JDBC program to create a table GRTGS (Message – Text), insert two greetings into the table, display the table contents, and drop the table. Assume the DSN name is GREETINGS. 2. Use JDBC API to do the following: • Create a table in Oracle with following structure. FriendName Text(20) Dob Date Details Text(20) PhoneNumber Number • Insert the records • Show all the records from the table. 3. Write a program that takes values for BookName and BookId from the user on command prompt and inserts the values in the table Book assuming table to be already created. 4. Write a program that retrieves the records from Book having field Book ,BookName and BookId 5. Write a program that searches for record in table BOOK(BookName varchar2(25),BID number(2,5)) .The value for the BookName is taken from command prompt ,if record found “Record Found” message is displayed and the details regarding the respective Book is displayed else “Record Not Found” is displayed. 6. Write a JDBC program that accepts a table name and displays the total number of records in it. 7. Write a JDBC program that prints the names of all columns in a table that is given on the command line. 8. Write a JDBC program to change the name of a column. Table name is supplied on command line. 9. Create a database “EMPLOYEEDB.MDB” through Microsoft Access. Create a Data Source Name (DSN); give an appropriate name for DSN. Then write a single program to create a table EMPLOYEE (ENO – Integer, ENAME-Text, BPAY-double, ALLOWANCES-double, TAX-double, NETPAYdouble). Through the same program insert 5 records, and display the output in a tabular manner. NETPAY must be calculated and entered in the table using the formula: NETPAY = BPAY + ALLOWANCES – TAX. 10. Write a program that accepts an employee number (ENO) for the above database and if it is found in the table, prints its details, else prints “Record not found”. 11. Modify (alter) the above table (EMPLOYEE) so that it contains one more column called DESIGNATION. Give appropriate SQL query to update this column. Then display all records where designation is “Manager”. Page 6 of 7 mukeshtekwani@hotmail.com
  • 7. JDBC - 1 REVIEW QUESTIONS 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. What are the components of JDBC? Explain the three statement objects in JDBC Explain types of execute methods in JDBC with examples. Explain DriverManager class and its methods. What is DSN? How is it created? Explain steps for connectivity in JDBC Explain any 4 methods of PreparedStatement. Discuss the two-tier architecture for data access. Discuss the three-tier architecture for data access. What are its advantages over the two-tier architecture? Differentiate between Statement and PreparedStatement Explain different methods of ResultSet object. State the object which encapsulates the data retrieved from the database. State the method which is used to to get the value of the specified column of the current row from a database. State the method which is used to get the value of the specified column of the current row from a database. Which method is used to execute a SELECT query? Which method is used to execute DDL statements such as INSERT, UPDATE, and DELETE? Write short notes on: a. JDBC b. JDBC-ODBC Bridge c. Types of driver managers in JDBC d. PreparedStatement e. Transaction and savepoint Explain the following method, and also state the class/interface to which they belong: • next() • close() • forName() • createStatement() • executeUpdate() • prepareStatement() • getConnection() • getString() • getColumnCount() Prof. Mukesh N. Tekwani Page 7 of 7