Vous êtes sur la page 1sur 23

A Programmers Guide to Advanced Java Certification A Comprehensive Primer First Edition

Mohd.Arshad Ali

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 1

1. JDBC 2. SERVLET 3. JAVA BEAN 4. JSP 5. JSTL 6. Expression Language

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 2

JDBC

Q. Why DATABASE is required? Ans. 1.Developing programs which maintain and manage the data in native language was increasing complexity of program, thats why we need DATABASE. 2.In order to maintain and manage the data in a most simpler manner and efficient, so concept of database come to existence. 3.Using DATABASE, we can create the separate program, which are required the maintaining the data and managing the data from ELA(Enterprises level Application). Q. What is DATABASE? Ans. ->DATA BASE is a collection of one or more files for future references,i.e.DATABASE. ->Data base is the collection of programs using which we can execute the sql stmt and maintain & manage the data in the term of tables could be called DB. Q. Why JDBC? Ans. To create a connection b/w JAVA API to back end data base. STEP which followed by JDBC =========================== 1.Load the driver related class from h/d to ram using java program. 2.Create the connection to the driver from java program. 3. Transfer SQL statement in the form of java API(String class obj) to drivers from java program. 4.driver ,convert java api into its equivalent back-end database. 5.To make the driver send back-end database(sql converted stmt) and execute sql stmt at the back-end database. 6.Get o/p of the sql stmt from the back-end database in the java program. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 3

Q. What is JDBC? Ans. JDBC is the name of technology which provides an environment for connecting java program to back-end database and using database for maintaining and managing data from java program,i.e.JDBC. Note ====There is no full form of JDBC, becoz it is the trademark of Sun Micro System. Q.JDBC Architecture? Ans. jdbc.jpg

//About Trademark Q. What is Enterprises Level Application? Ans. Those application which make for business purpose, that types of application is knows as ELA. ==>ELA is also known as Business Level Application. ==>There are 3 parts which is maintain by ELA: 1.Presentation part view(html) 2.Bussiness Logic(programming) 3.Model part(database)

Q. Why Driver? Ans .In order to communicate with back-end database from the java program, we need some mediator(interface) b/w java program and backend database. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 4

String a=new String("Select * from emp"); Q. What is Driver? Ans. Driver is nothing but it is the collection of predefined program which can convert the SQL statement(which is represent as a String class's object)into its equivalent back-end database,i.e.Driver. Q. Types of Driver. Ans .There are 4 types of drivers in jdbc.... 1.JDBC-ODBC Bridge Driver(Type-1 driver) ===================================== type1.jpg a.first part of this driver made in java by sun micro system and second part of this driver made in c and c++ by Micro soft.

Advantage ========= 1.When java first come out,this was very useful driver becoz most database supported ODBC access but now type-1 recommended only for experiment purpose or when no other alternative is available. 2.provide connectivity with MS access/excell. Drawback ======== 1.Windows XP OS dependent. 2.large number of conversion layer as compare type2,3,4 drivers. 3.limited database can be connected. 4.convert sql statement into its corresponding back end database MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 5

is slow becoz of that there are so many number of conversion layers. 2.Part Java or Part Native Driver ot Type-2 driver type2.jpg Outdated.

3.Intermediate data access Driver or type-3 driver type3.jpg outdated.

4.type-4 driver or pure java driver or Thin driver type4.jpg

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 6

a. This is the highest performance driver available for database. b. This is usually provide by the db vendors it self. c. This kind of driver is extremely flexible, because of that there is only one conversion layer. d. You dont need to install special software to use type-4 driver. Q. which Programming language used in make the Drivers. Ans. driver Ist part IInd part Type-1 java C & C++ Type-2 java C & C++ Type-3 java C & C++ Type-4 java java Q.Which driver should be used? Ans. 1.If u are using only one type of database in yr application,such as Oracle,MySQL,Sybase etc preferred driver is Type-4. 2.If yr java application is accessing multiple type of database at same time, type-3 is preferred driver. 3.Type-2 drivers are useful in situations where a type-3 and type-4 driver is not available yet for yr database. 4.type-1 driver is not recommended for application development,it use only for testing purpose.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 7

Connectivity with oracle with type-1 MS Access with type-1 oracle with type-4 MySQL with type-4 MS Excell with type-1 Q. Why DSN is required. Ans. 1.If we want to use type-1 driver, we must need to create DSN. 2.Only for mapping. 3.to explicitly mentioned the database to which exactly the driver sql stmt send. Q. What is DSN. Ans. 1. DSN stands for DATA SOURCE NAME. 2. DSN is nothing but a mapping name, using which a java program & sun driver (type-1 driver) would be locating the back-end database, is called DSN. Q. Great Explanation Class.forName() a. working of Class.forName() b. internal mechanism for loading driver class. Q. Step required for implementing type-1 driver(oracle). A. configure the driver. click on Control Panel-->Administrative tools-->Data Source--> System DSN--->Add-->"Micro Soft ODBC for Oracle"--> finish---> DSN name="any name"--->OK--OK. B. Loading the driver(driver related class) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 1.load the .class file of JdbcOdbcDriver 2.static block execute of JdbcOdbcDriver 3.internally create the object of JdbcOdbcDriver in static block of JdbcOdbcDriver. 4.internally call registerDriver() method call. 5.to assign reference of JdbcOdbcDriver into JdbcOdbcDriver type ,which is member of DriverManager class. C. Make the driver to create connection

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 8

java.sql.Connection a=java.sql.DriverManager.getConnection("jdbc:odbc:DSN_NAME","scott","tiger"); java.sql.Connection a=java.sql.DriverManager.getConnection("jdbc:odbc:DSN_NAME");//for MS ACCESS jdbc=protocol odbc=name of driver D. Define SQL stmt in the form of String class's object. String sql="Insert into abc values("+101+",'ARSHAD','KANPUR')"; E. Send the SQL stmt. java.sql.Statement a1=a.createStatement(); int i=a1.executeUpdate(sql); F. Excecute the query and get the result. get the integer information from executeUpdate() method.

Q. Step required for implementing type-4 driver(oracle). A. configure the driver. //set classpath=C:\oracle\product\10.2.0\db_1\jdbc\lib\classes12.jar; B. Loading thr driver Class.forName("oracle.jdbc.driver.OracleDriver"); C. Make the driver to create connection DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); port no=1521(C:\oracle\product\10.2.0\db_1\network\ADMIN\tnsnames.ora) host=localhost(C:\oracle\product\10.2.0\db_1\network\ADMIN\tnsnames.ora) service name(database name)=orcl(C:\oracle\product\10.2.0\db_1\network\ADMIN\tnsnames.ora)

D. Define SQL stmt in the form of String class's object E. Send the SQL stmt F. Excecute the query and get the result Q. Step required for implementing type-4 driver(mysql). A. configure the driver. B. Loading thr driver MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 9

C. Make the driver to create connection D. Define SQL stmt in the form of String class's object E. Send the SQL stmt F. Execute the query and get the result

Q. Job of java.sql.DriverManager class. Ans. This class manage the list of database drivers and match the connection Request from java application to proper database driver. Q. Job of Connection interface. Ans.connection reference contains complete detail about path of database (send the sql stmt to back-end database). java.sql.Connection is the name of interface. Q. getConnection(String url,String un,String pw),getConnection(String url), Q. What is URL. Ans.To represent the address of the destination on the n/w,i.e.URL (Uniform resource locator) Q. What is protocol. Ans. Protocol is nothing but set of rule and regulation is called Protocol. Q. Why do we need Protocol(jdbc:odbc)? Ans. Because of that if we want to send the data from one domain(java program) to another domain(database),thats why we need protocol.

Q.Statement createStatement() method of Connection interface. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 10

Q.Demo example of JDBC. Q.Statement interface. Q.int executeUpdate() method. for DML query(insert,update,delete). Q.ResultSet executeQuery() method for DDL query(select). 1.ResultSet is the name of interface which is prsent in java.sql package. 2.reference variable of ResultSet type get is actual location where exactly database table is present. boolean next() ==============to locate current row of the table and move to the cursor to the next row,if next row is prsent the return "true" else "false"; 1)int getInt(int columnno),int getInt(String cname) 2)float getFloat() 3)String getDouble() 4)String getString() (Connectinity with type-1 & type-4 driver) 1.oracle with type-1 2.oracle-with type-4 3.mysql with type-4 4.MS access with type-1

Q.WAP in jdbc for insert the details. Q.WAP in jdbc for insert the details and details input through the keyboard. Q.How to update the database table's row using JDBC program. Q.How to update the database table row using JDBC program through consol. Q.How to delete the database table's row using JDBC program. Q.How to delete the database table's row using JDBC program ,using input condition through keyboard. Q.java.sql.ResultSet interface Q.boolean next() method getInt(int colnumber) getInt(String colname) getFloat,getString,getDouble etc.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 11

Q.WAP in jdbc for get the details for specified table. 1.How to Netbeans IDE. 2.How to use MyEclips IDE. Q.java.sql.ResultSetMetatData (What ,Purpose of this interface). What==>java.sql.ResultSetMetatData is the name of interface using which we can get the information of data about data. like name of column,count the name,getColumntype ect. java.sql.ResultSetmetatData rs.getMetaData(); int getColumnCount(); String getColumnName(int i); String getColumnTypeName(int i); Q. WAP using ResultSetMetaData interface. Q. How to use accept the table name from consol, if table is present in data base then display the how many number of column, column name and column type ,if table name not present then display some message,i.e."table or view does not exist". Q. Drawback of java.sql.Statement interface Ans. if we are sending the data into the back-end database more than one time ,in this case ,every time java sql query statement go to driver and driver send the query to the back-end database. and then increase the load of driver, so we dont use java.sql.Statement interface for sending values into the back-end database for multiple time. Q. Advantage of java.sql.PreparedStatement interface over the Statement interface. Ans. if we are sending the data into the back-end database more than one time ,in this case ,every time not need to interact java sql query statement to driver .Using java.sql.PreparedStatement interface sql statement interact to the driver only once,so the load of driver will not increase, So we always prefer java.sql.PreparedStatement interface for sending the values into the back-end database for multiple time. Q. When do people prefer java.sql.Statement interface. Ans. If people want to send the data into database only one time, then prefer java.sql.Statement interface.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 12

Q. When do people prefer java.sql.PreparedStatement interface. Ans. If people want to send the data into database multiple time, then prefer java.sql.PreparedStatement interface.

Job of java.sql.PreparedStatement interface


Method of java.sql.PreparedStatement 1.void setInt(int parameterIndex,int value) 2.void setDouble(int parameterIndex,double value) 3.void setBoolean(int parameterIndex,Boolean value) 4.void setString(int parameterIndex,String value) etc. ("Insert into abc1 values(?,?,?)"; Note === instead of Statement s=c.createStatement(); this statement we will use PreparedStatement ps=c.prepareStatement("SQL statement"); Q.WAP in jdbc for insert the details using PreparedStatement interface. Q.How to update the database table row using JDBC program using PreparedStatement interface. Q.WAP in jdbc for get the details for specified table through java.sql.PreparedStatement. Q.WAP in jdbc for get the details for specified table and table name input through the keyboard. Q.WAP in jdbc for get the details for specified table and table name input through the keyboard and specified row(where clouse). Q.WAP in jdbc for get the multiple query details from databse using PreparedStatement input through the keyboard and specified row(where clause). Note ==== There are 3-different types of resultSet object available ,ther are: 1.Scrolable type ResultSet and java program Using this concept we can move the cursor pointer or cursor position according to our wishes.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 13

public static final int TYPE_SCROLL_SENSITIVE=1005 public static final int CONCUR_READ_ONLY=1007 Statement st= c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ _ONLY); ResultSet rs=st.executeQuery("Select * from emp"); while(rs.next()) { } 1)void afterLast() =================== Moves the cursor to the end of table row, just after the last row. 2)void beforeFirst() ====================Moves the cursor to the front of table row, just before the first row. 3)void first() ================= Moves the cursor to the first row in selected table. 4)void last() ================Moves the cursor to the last row in selected table. 5)boolean isBeforeFirst()==>is cursor present or not on the top possition 6)boolean isFirst()==>is cursor present or not on the first row 7)boolean isAfterLast();is cursor present or not on the bottom possition 8)boolean isLast()is cursor present or not on the last row 9)public boolean absolute(int row)==>move the cursor to the specified row. 10)public int getRow()==>return row number where cursor is pointing. 11)public boolean next()==>move the cursor to the next row. 2.Updatable type ResultSet and java program Using this concept we can update the table using ResultSet object with DLL query. public static final int TYPE_SCROLL_SENSITIVE=1005 public static final int CONCUR_UPDATABLE=1008

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 14

Statement st= c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDA TABLE); ResultSet rs=st.executeQuery("Select * from abc1 where idno=1003");

1)public void updateInt(int col_index,int data) 2)public void updateInt(String col_name,int data) 1)public void updateDouble(int col_index,double data) 2)public void updateDouble(String col_name,double data) 1)public void updateString(int col_index,String data) 2)public void updateString(String col_name,String data) etc. updateRow();

if we enter correct idno then successfully updated.

3.InSensitive type ResultSet and java program(By default)

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 15

BATCH PROGRAMMING
Q. Batch Programming(allow only dml operation) Purpose of Batch programming whenever we required multiple sql stmt(DML) execute in database at the same point of time, then we use Batch programming. Q. What is Batch? Ans. Batch is nothing but it is the group. group==(sql query group(dml only)). "Group of dml sql stmt ,i.e.Batch Programming." DML=Data manipulation Language(insert ,delete,update) Note We cannot use "Select * from tablename" query. How to do There are two ways to use Batch Programming: 1.Using Statement interface 2.Using PreparedStatement interface How to use Statement interface with batch programming some important methods in Statament interface. 1.public void addBatch(String sql); 2.int[] executeBatch() Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts. that means return 1(one),how many number of time addBatch() query successfully executed. How to use PreparedStatement interface with batch programming some important methods in PreparedStatament interface. 1.public void addBatch(); 2.int[] executeBatch() Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 16

Transaction Property
Q. Commit and Rollback. 1.Commit==>Save changes 2.Rollback==>Undo Whenever we send the dml sql stmt into database through the java program then internally set commit property is true, that means we cannot rollback the data of the table using "rollback " command. setAutoCommit(true) on connection object; eq. 1.notepad 2.ATM Q. What is Commit? Ans. Commit means saving the changes at the back-end database permanently. Q. How to use commit command on oracle? Ans. sql>commit; Q. What is Rollback? Ans. Rollback means undoing the changes at the back-end database, Is called Rollback. Q. How to use rollback command on oracle? Ans. sql>rollback; NOTE === 1. Bydefault Connection interface object is auto commit(true), that means we cannot rollback the data which send though the java program. 2.Whenever we required that rollback is work properly then we must setAutoCommit(false) explicitly. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 17

There are some method of Connection interface for transaction: 1.void setAutoCommit(boolean a)//false 2.void commit() 3.void rollback() 4.boolean getAutoCommit();

Stored Procedure
Q (CallableStatement interface) Stored Procedure Stored procedure is nothing but it is one of the most useful mechanism to create procedure in the database and call from java program is called Stored Procedure. Q. Why do we use Stored Procedure? Ans. To reduce network load, every time we need not send more than one sql stmt. thats why we use Stored Procedure. Q. What is procedure? Ans 1.Procedure is a function or method of database. 2.Group of sql statement in database. 3.Using PL/SQL programming ,we create procedure. Q. When do people prefer stored procedure? Ans. eg. Whenever ,user want to get the allounce, gross salary etc. from the database, we need not to create any logic to calculate allounce,gross salary in the java program, we will create separate procedure for calculate the allounce and gross salary,and then we can get allounce and gross salary in the java program. Advantage 1.Using Stored procedures the processing of data at the back-end database would be faster. 2.Overhead on the java program can be reduce. Drawback 1.Each and every database contains our own syntax of creating procedure, ,So if we want to change the database in future of the particular application then problem occur. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 18

Note Stored Procedure doesnt support by MS Access. Q. What is the API of Stored procedure in java? Ans. java.sql.CallableStatement interface CallbleStatement extends PreparaedStatement PreparedStatement extends Statement Q. How to get object reference of java.sql.CallableStatement interface? Ans. CallableStatement cst=con.prepareCall("{procedure calling syntax }"); cst.execute(); execute() method belong to the java.sql.PreparedStatement interface. but here "execute()" method we are calling "CallableStatement reference", actually CallableStatement is the sub interface of PreparedStatement interface. 1. setInt(String parametername,int data); setInt(int parameternumber,int data); etc.setXXX() method. parametername=means "IN" or "OUT" 2. registerOutParameter(int outparameternumber,int sqlTYPE) sql types ,we can get==java.sql.Types class contains psf int INTEGER; ........FLOAT; ........DOUBLE ........BOOLEAN ........VARCHAR .......DATE .......CHAR .......BLOB 3. and get the details by the out parameter. getDouble(int indexofoutparamter) getInt(int indexofoutparamter) getXXX()..............

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 19

There are 4 types of procedure:


1. Zero Parameterized Procedure Those procedure which doesnt contains any parameter is called Zero Parameterized Procedure Q.How to create Zero Parameterized Procedure in Oracle? Ans. Example: SQL> SQL> create or replace 2 procedure prc1 3 Is 4 Begin 5 Update abc1 set name='MUSTAQ' where id=101; 6 End prc1; 7 / Procedure created. Q. Write the java program to call Zero Parameterized Procedure? Ans.

2.In-Procedure it is just like a method of java which is parameterized but void return type like pass the 'idno' or any conditional data as a parameter.. Q.How to create IN Parameterized Procedure in Oracle? Ans. SQL> r/ 1 create or replace 2 procedure prc2(aa IN number) 3 Is 4 Begin 5 Update abc1 set name='SAEED' where id=aa; 6* End prc2; Procedure created. Q. Write the java program to use IN Parameterized Procedure? MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 20

3.Out-Procedure it is just a method of java which is contains zero parameter return.... like max, min, count, sum etc. Q. How to create OUT Parameterized Procedure in Oracle? Ans. SQL> create or replace 2 procedure prc3(abc OUT number) 3 Is 4 Begin 5 Select count(id) into abc from abc1; 6 End prc3; 7 / Procedure created. Q. Write the java program to use OUT Parameterized Procedure? Ans.

4.In-Out Procedure it is just a method of java which is parameterized as well as return type .... like max, min, count etc. Q. How to create IN and OUT Parameterized Procedure in Oracle? Ans. SQL> create or replace 2 procedure prc4(x IN number,y OUT number) 3 Is 4 Begin 5 Select max(id) into y from abc1 where id>=x; 6 End prc4; 7 / Procedure created. Q. Write the java program to use IN and OUT Parameterized Procedure? Ans.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 21

HOW TO STORE AND RETRIEVE IMAGE IN/FROM DATABASE Q. Write a java program to insert image into databases. Ans. import java.sql.*; import java.io.*; public class InsertBlobEx { public static void main (String s[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); String url=jdbc:oracle:thin:@localhost:1521:orcl"; String un=scott; String pw=tiger; Connection con=DriverManager.getConnection(url,un,pw); PreparedStatement ps=con.prepareStatement("insert into emp3 values(?,?,?)"); ps.setInt(1,103); ps.setString(2,"ZAHEER"); File f=new File("G:\\CD\\2011 Convogation\\DSC03397.JPG"); FileInputStream fis=new FileInputStream(f); System.out.println(f.length()); ps.setBinaryStream(3,fis,(int)f.length()); int i=ps.executeUpdate(); System.out.println("Record inserted,count:"+i); con.close(); } } Output is:Record inserted 1.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 22

Q. Write a java program to retrieve image from databases. Ans. import java.sql.*; import java.io.*; public class ReadBlobEx { public static void main(String s[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tige r"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp3 where idno=103"); while(rs.next()) { int empno=rs.getInt(1); String ename=rs.getString(2); InputStream is=rs.getBinaryStream(3); FileOutputStream fos=new FileOutputStream("mohsin.jpg"); int i=is.read(); while(i!=-1) { System.out.println(i); fos.write(i); i=is.read(); }} System.out.println("image is retrieve"); con.close(); } } Output is: image is retrieve

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 23

Vous aimerez peut-être aussi