Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JDBC Exam Q & A

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Exam on JDBC and SQL Queries

Q1) Which method is used to execute select Queries?


a)executeUpdate()

b)executeQuery()

c)updateExecute()

d)queryExecute()

Ans) b

Q2) Which method is used to execute non-select Queries?


a)executeUpdate()

b)executeQuery()

c)updateExecute()

d)queryExecute()

Ans) a

Q3) Identify the class below?


a)com.mysql.jdbc.Driver

b)java.sql.Driver

c) a and b

d)None of the above

Ans) a

Q4) Identify the interface below?


a)com.mysql.jdbc.Driver

b)java.sql.Driver

c) a and b

d)None of the above

Ans) b
Q5) What is the correct sequence to create a database connection?
i. Import JDBC packages.

ii. Open a connection to the database.

iii. Load and register the JDBC driver.

iv. Execute the statement object and return a query resultset.

v. Create a statement object to perform a query.

vi. Close the resultset and statement objects.

vii. Process the resultset.

viii. Close the connection.

a)i, ii, iii, v, iv, vii, viii, vi

b)i, iii, ii, v, iv, vii, vi, viii

c)ii, i, iii, iv, viii, vii, v, vi

d)i, iii, ii, iv, v, vi, vii, viii

Ans) b
Explanation: To create a database connection in Java, we must follow the sequence given below:

Import JDBC packages.

Load and register the JDBC driver.

Open a connection to the database.

Create a statement object to perform a query.

Execute the statement object and return a query resultset.

Process the resultset.

Close the resultset and statement objects.

Close the connection.


Q6) What are the major components of the JDBC?
a)DriverManager, Driver, Connection, Statement, and ResultSet

b)DriverManager, Driver, Connection, and Statement

c)DriverManager, Statement, and ResultSet

d)DriverManager, Connection, Statement, and ResultSet

Ans) a

Q7) Which of the following method is static and synchronized in


JDBC API?
a)prepareCall()

b)executeUpdate()

c)executeQuery()

d)getConnection()

Ans) d

Q8) Which of the following is not a valid statement in JDBC?


a)Statement

b)PreparedStatement

c)QueryStatement

d)CallableStatement

Ans) c

Q9) What does setAutoCommit(false) do?


a)It will not commit transactions automatically after each query.

b)It explicitly commits the transaction.

c)It never commits the transactions.

d)It does not commit transaction automatically after each query.

Ans) b
Q10) What should be the correct order to close the database
resource? What should be the correct order to close the database
resource?
a)Connection, Statements, and then ResultSet

b)ResultSet, Connection, and then Statements

c)Statements, ResultSet, and then Connection

d)ResultSet, Statements, and then Connection

Ans) d

Q11) What is JDBC Save point?


a)An intermediate or checkpoint in a transaction

b)A point where we can store queries

c)A point where the JDBC application starts execution

d)A memory where we can store transaction

Ans) a

Q12) How many stages are used by Java programmers while using
JDBC in their programs?
a)3

b)2

c)5

d)6

Ans) d

Explnation:

There are following stages in a JDBC program:

Register the driver

Connecting to a database

Preparing SQL statements in Java

Executing the SQL statements on the database

Retrieving the results

Closing the connection


Q13) What is blob in the following statement?
create table profilepic(photo blob);

a)Variable

b)Object

c)Data type

d)Keyword

Ans) c

Q14) Which data type is used to store files in the database table?
a)BLOB

b)CLOB

c)File

d)Both a and b

Ans) b

Q15) Which of the following interface provides the commit() and


rollback() methods?
a)Statement Interface

b)ResultSet Interface

c)Connection Interface

d)RowSet Interface

Ans) c

Q16) How many statement objects can be created using a


Connection?
a)2

b)1

c)3

d)Multiple

Ans) d
Q17)Draw JDBC architecture for the databases oracle,mysql and
MS-SQL servers?
Ans) jdbc_architecture.png

Q18)Write steps to connect database in java using JDBC (Each is


one line sentence in text)
Ans)

i)Load and register the JDBC Driver

ii)Get the Connection

iii)Create the Statement

iv)Prepare ans execute the Query

v)Process the Result

vi)Close the database Connection

Q19)getConnection() method is present in which class?


Ans) "java.sql.DriverManager" class

Q20)Write some of the important classes and interfaces along with


package names which are used in java program for database
transactions?
Ans)

Classes

a)com.mysql.jdbc.Driver

b)java.sql.DriverManager

c)java.sql.Types

d)java.sql.Date

e)oracle.jdbc.driver.OracleDriver

Interfaces

a)java.sql.Connection

b)java.sql.Driver
c)java.sql.Statement

d)java.sql.PreparedStatement

e)java.sql.CallableStatement

f)java.sql.ResultSet

Q21)what is the default port number of MySQL Server?


Ans) 3306

Q22)What is the default port number of Oracle Server?


Ans) 1521

Q23)Which URL is used to connect JAVA Application with MySQL


database Server?
Ans) "jdbc:mysql://localhost:3306/<database_nme>"

Q24)Which URL is used to connect JAVA Application with Oracle


database Server?
Ans) "jdbc:oracle:thin:@localhost:1521/XE"

Q25)what is the difference between "com.mysql.jdbc.Driver" and


"java.sql.Driver"?
Ans) "com.mysql.jdbc.Driver" is a class whereas "java.sql.Driver" is an interface

Q26)executeQuery() returns which Object?


Ans) "ResultSet" Object

Q27)What is the purpose of Statement,PreparedStatement and


CallableStatement?
Ans)

Statement: Use this for general-purpose access to your database. It is useful when we are using
static SQL statements at runtime. The Statement interface cannot accept parameters.

PreparedStatement: It represents the pre-compiled SQL statements that can be executed multiple
times.

CallableStatement: It is used to execute SQL stored procedures.


Q28)How to move to last row of the table using ResultSet
Object(cursor)?
Ans) rs.last();//where rs is the ResultSet Object

Q29)Write a query to find the number of records in a "student"


table?
Ans) select count(*) from student

Q30)Write a query to find the minimum and maximum salary from


employee table?
Ans) select min(sal),max(sal) from employee

Q31)Write a query to find the total salary of employees from


employee table?
Ans) select sum(sal) from employee

Q32)Write a query to find the average salary of employees from


employee table?
Ans) select avg(sal) from employee

Q33)Write a query to combine two


strings("ashokit","technologies")?
Ans) SQL> select concat('ashokit','technologies') from dual;

Q34)Write a query to display only "it" from "ashok it


technologies"?
Ans) SQL> select substr('ashok it technologoes',7,2) from dual;

Q35)Write a query to display name and number of characters of


name from student table?
Ans) SQL> select sname,length(sname) from student;

Q36)Write a query to see the date?


Ans) SQL> select sysdate from dual;
Q-37) Write a query to see the name and experience in months of
the emplooyee in a company?
Ans)

SQL> select name,doj,round(Months_Between(sysdate,doj)) "Experience in months" from emp;

Q-38) Name all the constraints in Oracle database?


Ans)

a)NOT NULL

b)UNIQUE

c)PRIMARY KEY

d)FOREIGN KEY

e)CHECK

f)DEFAULT

Q39)Write a query to insert data dynamically(Using & symbol)?


Ans)

SQL> insert into emp values(&eid,'&name',&sal);

Enter value for eid: 2

Enter value for name: raghu

Enter value for sal: 40000

Q-40) Write a query to display second highest salary from "emp"


table?
Ans) SELECT MAX(sal) AS salary FROM emp WHERE sal IN(SELECT sal FROM emp MINUS SELECT
MAX(sal) FROM emp);

OR

SELECT MAX(sal) AS salary FROM emp WHERE sal <> (SELECT MAX(sal) FROM emp);
Q41)Write a query to display empno,ename,manager and location
from below data using joins?

SQL> desc emp;

Name Null? Type

----------------------------------------- -------- ----------------------------

EMPNO NUMBER(6)

ENAME VARCHAR2(10)

JOB VARCHAR2(10)

MGR NUMBER(6)

DEPTNO NUMBER(6)

SQL> desc dept;

Name Null? Type

----------------------------------------- -------- ----------------------------

DEPTNO NUMBER(2)

DNAME VARCHAR2(15)

LOC VARCHAR2(12)

Ans)

SQL> SELECT e.empno, e.ename, e.mgr AS Manager,d.loc as location FROM emp e LEFT JOIN
dept d ON d.deptno = e.deptno ORDER BY d.deptno;
Q42)Write a java program to insert a row into the database?
Ans)

import com.mysql.jdbc.Driver;

import java.sql.*;

public class InsertData{

private static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

private static final String DB_USER="root";

private static final String DB_PWD="";

private static final String INSERT_SQL="insert into emp values(3,'emp3',70000)";

public static void main(String[] args)throws Exception{

//step1:Load the Driver class

Class.forName("com.mysql.jdbc.Driver");

//step2:Get Database Connection

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

System.out.println(con);

//step3:Create the Statement

Statement stmt=con.createStatement();

//step4:Execute the Query

int rowsEffected=stmt.executeUpdate(INSERT_SQL);

//step5:Process the Result

System.out.println("Records Insered:"+rowsEffected);

//step6:Close the Connection

con.close();

}
Q-43) Write a java program to get the data from the database and
display on the console?
Ans)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

import java.sql.ResultSet;

public class GetDataDemo{

public static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

public static final String DB_USER="root";

public static final String DB_PWD="";

public static void main(String[] args)throws Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from student");

while(rs.next())

System.out.println(rs.getInt(1));

System.out.println(rs.getString(2));

stmt.close();

con.close();

Q44)Write a java program to insert a row using


PreparedStatement?
Ans)

import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.PreparedStatement;

public class InsertDataDemo{

public static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

public static final String DB_USER="root";

public static final String DB_PWD="";

public static void main(String[] args)throws Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

String query="insert into emp(id,name,sal) values(?,?,?)";

PreparedStatement pstmt=con.prepareStatement(query);

pstmt.setInt(1,11);

pstmt.setString(2,"ashok");

pstmt.setInt(3,100000);

pstmt.executeUpdate();

pstmt.close();

con.close();

System.out.println("Data inserted successfully");

}
Q-45)Write a java program to get the data from the database and
display using PreparedStatement?
Ans)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

public class GetDataPrepareDemo{

public static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

public static final String DB_USER="root";

public static final String DB_PWD="";

public static void main(String[] args)throws Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

String query="select * from emp";

PreparedStatement pstmt=con.prepareStatement(query);

ResultSet rs=pstmt.executeQuery(query);

while(rs.next())

System.out.println(rs.getInt(1)+"---"+rs.getString(2)+"---"+rs.getInt(3));

pstmt.close();

con.close();

}
Q-46)Write a java program to insert 5 rows into database table at a
time as a batch?
Ans)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

public class BatchUpdates{

public static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

public static final String DB_USER="root";

public static final String DB_PWD="";

public static void main(String[] args)throws Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

Statement stmt=con.createStatement();

stmt.addBatch("insert into student values(1,'student1')");

stmt.addBatch("insert into student values(2,'student2')");

stmt.addBatch("insert into student values(3,'student3')");

stmt.addBatch("insert into student values(4,'student4')");

stmt.addBatch("insert into student values(5,'student5')");

stmt.executeBatch();

stmt.close();

con.close();

System.out.println("Data inserted successfully");

}
Q-47) Write java program to select all records from the table using
CallableStatement?
Ans)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.CallableStatement;

public class CallableDemo{

public static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

public static final String DB_USER="root";

public static final String DB_PWD="";

public static void main(String[] args)throws Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

/*

create a procedure as below

MariaDB [advjdb]> create procedure getData()

-> BEGIN

-> select * from emp;

-> END //

Query OK, 0 rows affected (0.005 sec)

*/

CallableStatement cstmt=con.prepareCall("{call getData}");

System.out.println(cstmt);

con.close();

}
Q-48) Write a java program to call the procedure using IN and OUT
Parameters?
Ans)

import java.sql.*;

public class CallableDemo2{

public static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

public static final String DB_USER="root";

public static final String DB_PWD="";

public static void main(String[] args)throws Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

Scanner sc=new Scanner(System.in);

System.out.println("Enter book price:");

int bookPrice=sc.nextInt();

/*

create a procedure as below

MariaDB [advjdb]> DELIMITER $$

MariaDB [advjdb]> create procedure getBookNameByPrice(IN bprice INT,OUT bname


VARCHAR(100))

-> BEGIN

-> select book_name into bname from books where book_price<=bprice;

-> END $$

*/

CallableStatement cstmt=con.prepareCall("{call getBookNameByPrice(?,?)}");

cstmt.setInt(1,bookPrice);

cstmt.registerOutParameter(2,Types.VARCHAR);

cstmt.executeQuery();

System.out.println(cstmt.getString(2));

con.close();

}
Q-49) Write a java program to insert an image into the database?
Ans)

import java.io.*;

import java.sql.*;

public class InsertImage{

private static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

private static final String DB_USER="root";

private static final String DB_PWD="";

public static void main(String[] args)throws Exception{

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

PreparedStatement pstmt=con.prepareStatement("insert into imgtab values(?,?,?)");

pstmt.setInt(1,104);

pstmt.setString(2,"stud4");

File f=new File("bird.jpg");

FileInputStream fis=new FileInputStream(f);

pstmt.setBinaryStream(3,fis,(int)f.length());

int num=pstmt.executeUpdate();

System.out.println(num+" row inserted successfully");

Q-50) Write a java program to retrieve the image from the


database and store in a file in our directory?
Ans)

import java.io.File;

import java.io.FileOutputStream;

import java.sql.*;

public class RetrieveImage{

private static final String DB_URL="jdbc:mysql://localhost:3306/advjdb";

private static final String DB_USER="root";

private static final String DB_PWD="";


public static void main(String[] args)throws SQLException,Exception{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from imgtab");

rs.next();

System.out.println(rs.getInt(1));

System.out.println(rs.getString(2));

byte imgarr[]=rs.getBytes(3);

FileOutputStream fos=new FileOutputStream("dbimg.jpg");

fos.write(imgarr);

fos.close();

con.close();

System.out.println("Image retrieved successfully");

You might also like