Question

What is the difference between statement ,Prepared Statement and callable statement . In what sit...

what is the difference between statement ,Prepared Statement and callable statement .

In what situations do we use these three? in what situations they are preferred . Also please write the syntax of connection the database. Suppose i have database:url and datasource named C://databasesourceurl databasename and password:password@123

please tell how to execute statement and how the resultset statement is written .Also if i have to show/display all the records till the end of the database we will use result rs.next() methor result.hasnext()

please tell in what situations do we need to use rs.next() and rs.hasnext()

please tell in easy words without copy pasting . please write answer in your own words because i am not understanding.

Language is Core java .

0 0
Add a comment Improve this question Transcribed image text
Answer #1

statement:
Suppose in you java program,you want to run a particular sql query like "CREATE TABLE EMPLOYEE(ID NUMBER NOT NULL, NAME VARCHAR)" ,so this query is not going to change dynamically as its very constnat definiton for table creation,you can use like a statement

Below is sample code:

package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test{

public static void main(String a[]){

Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
,"user","password");
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE EMPLOYEE(ID NUMBER NOT NULL, NAME VARCHAR)");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try{
if( stmt!= null) stmt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
}
}

Prepared Statement:
Now you have the table created and wanted to insert some data inside that employee table,so one way is like you can use statement
i.e insert into employee values(1,"A");
but in above the above statement is constant and consider a scenario where you want to populate data dynamically i.e get the value from
some login page and poulate in table in that case you cant simply hardcode it,you may need to use prepared statement like below:

String insertTableSQL = "INSERT INTO EMPLOYEE"
       + VALUES"
       + "(?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
//this corresponds to emp_id column
preparedStatement.setInt(1, 2);
//this corresponds to name column
preparedStatement.setString(2, "B");
// execute insert SQL stetement
preparedStatement .executeUpdate();

CallableStatement:
This is totally used for stored procedure,CallableStatement is used to execute the stored procedures. CallableStatement extends PreparedStatement.
Below is the code:

package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test{

public static void main(String a[]){

Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
,"user","password");
//Emp is a stored procedure here
String sql = "{call Emp(?, ?)}";
stmt = conn.prepareCall(sql);
  
//Bind IN parameter first, then bind OUT parameter
int empID = 102;
stmt.setInt(1, empID); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
  
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();

//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Emp Name with ID:" +
empID + " is " + empName);
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try{
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
}
}

rs.next() example:

package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test{

public static void main(String a[]){

Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
,"user","password");
Statement stmt = connection.createStatement();
String selectquery = "select name from employee";
ResultSet rs = stmt.executeQuery(selectquery);
//using rs.next to ietrate over all records
while(rs.next()){
System.out.println("Emp Name :" + rs.getString("name"));
}
}
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try{
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
}
}

hasnext() is used with iterators over collections,not specific to resultset.

You can see supported method by Resultset in below link:

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html

Below is example of iterator:

import java.io.*;

import java.util.*;

  

class Test {

    public static void main(String[] args)

    {

        ArrayList<String> list = new ArrayList<String>();

  

        list.add("A");

        list.add("B");

        list.add("C");

        list.add("D");

        list.add("E");

  

        // Iterator to traverse the list

        Iterator iterator = list.iterator();

  

        System.out.println("List elements : ");

//checking if iterator has any more elements then see the content

//if you find any element then only fetch it using hasnext

        while (iterator.hasNext()){

            System.out.print(iterator.next() + " ");

        System.out.println();}

    }

}

Hope it helps.

Thanks

Add a comment
Know the answer?
Add Answer to:
What is the difference between statement ,Prepared Statement and callable statement . In what sit...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am learning about compilers and am trying to understand what goes on in the separate...

    I am learning about compilers and am trying to understand what goes on in the separate phases. The questions I have are dealing with a 2-phase compiler. So, the front-end and the back-end. In the front-end is where we have the lexical analysis, syntax analysis, and semantic analysis. In the back-end is where we have instruction selection, register allocation, and instruction scheduling. I am given some situations that produce errors and told to determine if the error could be detected...

  • For this set of Review Questions, we will create and use a database for the Wedgewood...

    For this set of Review Questions, we will create and use a database for the Wedgewood Pacific Corporation (WPC) that is similar to the Microsoft Access database we created and used in Chapters 1 and 2. Founded in 1957 in Seattle, Washington, WPC has grown into an internationally recognized organization. The company is located in two buildings. One building houses the Administration, Accounting, Finance, and Human Resources departments, and the second houses the Production, Marketing, and Information Systems departments. The...

  • Please do not delete the questions. 1. What is the purpose of a database? 2. What...

    Please do not delete the questions. 1. What is the purpose of a database? 2. What is the reason to use a database over a spreadsheet? 3. Based on the previous answers (#1 & #2), there is a simple rule of thumb. A spread sheet is used when there is _________________________. A database is used when there are _________________________. 4. Please answer followings. a) A group of 8 bits is called a ____________ (from Chapter 4). b) The answers of...

  • Please make it sure your answers are meet what question needs with details I do not accept (copy ...

    Please make it sure your answers are meet what question needs with details I do not accept (copy / post) Using NetBeans IDE and write a CLI application that uses the BufferedWriter to write data to the file named "CustomerList.txt". =========================================================================== The application should follow this information A. Create a program that allows a user to input customer records (ID number, first name, last name, and balance owed) and save each record to a file. Save the program asWriteCustomerList.java.When you...

  • A 20 year, 8% semi-annual coupon bond with a par value of $1,000 may be called...

    A 20 year, 8% semi-annual coupon bond with a par value of $1,000 may be called in 10 years at a call price of $1,100. The bond sells for $1,200. e. How would the price of the bond be affected by a change in the going market interest rates? Please show work ( by adding numbers or CELL with formula if needed). Thank you, will rate. L M N I e a A 20 year, 8% semi-annual coupon bond with...

  • Topic: Marshall's corporate culture Speaker 1: Corporate culture is definitely unique. We have definitely hand that...

    Topic: Marshall's corporate culture Speaker 1: Corporate culture is definitely unique. We have definitely hand that to our human resources department but also building around the company we have a very strong mission statement that says we're here to make the best product possible and we're also here to do it in the most environmentally friendly way. People come to the company saying, "Wow, I'm not just here to have a job. I'm not here to make money." We're all...

  • Please Use C++ Language. Thank you. Please I need the actual code. Donot post psudocode!! ​And...

    Please Use C++ Language. Thank you. Please I need the actual code. Donot post psudocode!! ​And also I have codes but just donot work so make sure that it works. Requested files: CrosswordGenerator.cpp, CrosswordGenerator.h, CrosswordGenerator_test.cpp CrosswordGenerator - Write a program that helps to generate a crossword puzzle by organizing words that share letters.   For this assignment, you will write a program that forms the basis of a crossword puzzle generator. In order to create a crossword puzzle you need to...

  • Please help ! Concepts to be familiar with: 1. Difference between populations (parameters) and samples (statistics):...

    Please help ! Concepts to be familiar with: 1. Difference between populations (parameters) and samples (statistics): definitions and notation differences 2. Descriptive v. inferential statistics. What are they? What are their limitations? 3. Independent Variables (IVs) and Dependent Variables (DVs): definitions and how to recognize which is which in a study description 4. Discrete vs. continuous variables, apparent vs. real limits 5. Scales of measurement (N,O,I,R). Know what they are and examples of each. 6. Frequency tables: a. X, f,...

  • Need help with this project please! Please name the compiler and software used, would really appr...

    Need help with this project please! Please name the compiler and software used, would really appreciate that information. Don't bother doing the report section on this assignment either. Me and my group will handle it. This is a group project. Group size should be exactly 2 (unless approved earlier by the instructor). Only ne mi imi ma Design a security architecture for a smart electric metering infrastructure. Smart electric meters have embedded hardware for cellular connectivity, and are able to...

  • Interfaces 1. What is inside an interface definition? What does a class do to an interface...

    Interfaces 1. What is inside an interface definition? What does a class do to an interface and what keyword is involved? How does a class do this to an interface (what should we find in the class)? Can an interface have a generic parameter? How do you instantiate an interface as an object? What methods can’t you use on an interface type? Abstract Data Types 2. What does an ADT define? Does an ADT specify programming language and/or data structures...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT