Você está na página 1de 7

1

DATABASE CONNECTIVITY TO MYSQL


Type A: Very Short Answer Questions
1 How is database connectivity useful?
Ans. Database connectivity provides methods for querying and updating data in a database.
2 How does Java application connect to a database? Name the technology only.
Ans. JDBC (Java Database Connectivity)
3 Expand ODBC and JDBC.
Ans. ODBC Open Database Connectivity
JDBC Java Database Connectivity
4 What is connection?
Ans. A connection is the session between the application program and the database. To do anything with database, one
must have a connection object.
5 What does a Statement Object do?
Ans. The Statement object is the object used for executing one static SQL statement on the associated database-table and
returning the results it produces.
6 What is result set?
Ans. A result set refers to a logical set of records that are fetched from the database by executing a query and made
available to the application program.
7 What for a Class.forName () used?
Ans. It is used to create an instance of a driver and register it with the DriverManager. After loading the driver,
DriverManager instance is available for making a connection with a DBMS.
8 What does DriverManager do?
Ans. Driver Manager looks after managing the drivers for a JDBC application. When it is instantiated, it makes an attempt
to load the driver classes. When the method getconnection() is invoked, the driver manger attempts to locate the
suitable driver. The Driver Manager obtains the information about the drivers such as registering, locating, finding
the drivers loaded, setting the time to wait when it tries to get the connection to a database.
9 Name two commonly used drivers used for database connectivity from Java applications.
Ans. 1. class.forname(java.sql.Driver);
2. class.forname(com.mysql.jdbc.Driver);
10 Name methods to do the following:
(i) Open connection
(ii) Create statement
(iii) Move cursor forward by one row in a result set
(iv) Place cursor to first row in a result set
(v) Place cursor to last row in a result set.
Ans. (i) Open connection DriverManager.getConnection()
(ii) Create statement createStatement()
(iii) Move cursor forward by one row in a result set next()
(iv) Place cursor to first row in a result set first()
(v) Place cursor to last row in a result set last()
11 Which methods are used to execute SQL queries?
Ans. Following methods are used to execute SQL queries:
1. executeQuery()
2. executeUpdate()
12 Which package must be made part of Java application for database connectivity? Write statement to do so.
Ans. import java.sql.*;
13 Write a statement to register driver com.mysql.jdbc.Driver with DriverManager.
Ans. class.forname(com.mysql.jdbc.Driver);
14 Write a statement to open a connection object namely myCon for a MySQL database namely school.
Ans. Connection myCon=DriverManager.getConnection(jdbc:mysql://localhost:3306/school,root,pass);
15 Name the methods for the following:
http://cbsecsnip.in



2
(i) To fetch an integer value from a result set
(ii) To fetch a float value from a result set
(iii) To fetch a string value from a result set
(iv) To fetch a date value from a result set
(v) To fetch a boolean value from a result set
(vi) To fetch a double value from a result set
Ans. (i) To fetch an integer value from a result set getInt()
(ii) To fetch a float value from a result set getFloat()
(iii) To fetch a string value from a result set getString()
(iv) To fetch a date value from a result set getDate()
(v) To fetch a boolean value from a result set getBoolean()
(vi) To fetch a double value from a result set getDouble()
Type B: Short Answer Questions
1 What all tasks are performed using JDBC?
Ans. JDBC performs following tasks :
1. Establishing a connection with a database.
2. Sending SQL statements to database server.
3. Processing the results obtained.
2 What is following code doing?
String db=JoptionPane.showInputDialog ("Enter name of your MySql database...");
String DB_URL="jdbc:mysql://localhost/" +db;
Class.forName ("com.mysql.jdbc.Driver");
Connection con=Drivermanager.getConnection(DB_URL, "root","");
Ans.

When the code will execute it show the above dialogue box and enter the database name and then it stores the
database name in string variable db and open the connection.
3 What are the steps to connect to a database from with Java Application?
Ans. 1. Register the database driver by using the following statement:
Class.forName(driver class for that specific database)
2. Now create a database connection using the following statement:
Connection con = DriverManager.getConnection(url.username,password);
3. Now create a query using the following statement:
Statement stmt = Connection.Statement("SELECT*FROM TABLE NAME");
4. Execute the query as follows-
stmt.executeUpdate();
4 What is the difference between following two statements that use an object namely rs of ResultSet type?
(i) rs.getString(1);
(ii) rs.getString (Name);
Ans. rs.getString(1) is retrives the first column of the table whereas, rs.getString(Name) is retrieve the Name column of
the table.
5 What is wrong with following code (assuming that connection con is available)
:
String Qry="SELECT * FROM empl ; ";
Statement stmt=con.CreateStatement();
ResultSet rs=stmt.executeUpdate(Qry);
http://cbsecsnip.in



3
Ans. In the above code execuetUpdate() should be used if user is intended to do insert, update or delete process.
Otherwise we have to use executeQuery() for executing select statement.
6 What is the output of following code (consider the empl table given on page 332 in this chapter)
: //Connection con, Statement start created here
String qry="SELECT ename FROM empl" WHERE mgr = 8698; ";
ResultSet rs=stmt.executeQuery(qry);
rs.last();
String name=rs.getString(1); // WRONG LINE
JOptionPane.ShowMessageDialog(null,name);
Ans. Output of the above code will be a Dialog box displaying the name of the employee whose employee code is 869.
Note according to the this line String name=rs.getString(1); given in above will display the emp code
that is 8698, which is wrong according to table actually line should be String name=rs.getString(2);
7 Write code to connect to a MySQL database namely School and then fetch all those records from table Student
where grade is A.
Ans. i mpor t j ava. sql . *;
publ i c cl ass dat a_connect {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
t r y{

Cl ass. f or Name( " com. mysql . j dbc. Dr i ver " ) ;
Connect i on
con=Dr i ver Manager . get Connect i on( " j dbc: mysql : / / l ocal host : 3306/ school " , " r oot " , " " )
;
St at ement st mt =con. cr eat eSt at ement ( ) ;
St r i ng quer y=" SELECT ENO, ENAME, SALARY FROM st udent wher e
gr ade= A ; " ;
Resul t Set r s=st mt . execut eQuer y( quer y) ;
whi l e( r s. next ( ) )
{
St r i ng snoo=r s. get St r i ng( " SNO" ) ;
St r i ng name=r s. get St r i ng( " SNAME" ) ;
St r i ng cl ass=r s. get St r i ng( " CLASS" ) ;
Syst em. out . pr i nt ( " Rol l No: " +snoo) ;
Syst em. out . pr i nt ( " , Name: " +name) ;
Syst em. out . pr i nt l n( " , Cl ass: " +cl ass) ;
}
}
cat ch( Except i on e) {}
}
}
8 Predicate the output of following code: (Consider empl table of page 252)
:
//Connection and Statement objects are available
sql="SELECT empno, ename, job, sal FROM Empl; ";
ResultSet rs= stmt.executeQuery(sql);
while(rs.next())
{
int empno=rs.getInt("empno");
int sal=rs.getInt("sal");
String ename=rs.getString("ename");
String job=rs.getString("job");
System.out.print(""+rs.getRow());
System.out.print("EMPNO:"+empno);
System.out.print(", Ename:"+ename);
System.out.print(", job:"+job);
http://cbsecsnip.in



4
System.out.println(", Sal:"+sal);
}
Ans. 1EMPNO:8369, Ename:Smith, job:Clerk, Sal:800.00
2 EMPNO:8499, Ename:Anya, job:Salesman, Sal:1600.00
3 EMPNO:8521, Ename:Seth, job:Salesman, Sal:1250.00
4 EMPNO:8566, Ename:Mahadeven, job:Manager, Sal:2985.00
5 EMPNO:8654, Ename:Momin, job:Salesman, Sal:1250.00
6 EMPNO:8698, Ename:Bina, job:Manager, Sal:2850.00
7 EMPNO:8839, Ename:Amir, job:President, Sal:5000.00
8 EMPNO:8844, Ename:Kuldeep, job:Salesman, Sal:1500.00
9 EMPNO:8882, Ename:Shivansh, job:Manager, Sal:2450.00
10 EMPNO:8886, Ename:Anoop, job:Clerk, Sal:1100.00
11 EMPNO:8888, Ename:Scott, job:Analyst, Sal:3000.00
12 EMPNO:8900, Ename:Jatin, job:Clerk, Sal:950.00
13 EMPNO:8902, Ename:Fakir, job:Analyst, Sal:3000.00
14 EMPNO:8934, Ename:Mita, job:Clerk, Sal:1300.00
9 Find errors in the following code:
import java.sql *;
:
try {
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","wxyz");
Statement stmt=con.createStatement();
sql="SELECT empno, ename, job, sal FROM Empl; ";
ResultSet rs= stmt.executeQuery(sql);
}
catch(Exception e) { }
Ans. i mpor t j ava. sql . *;
:
t r y{
Connect i on
con=Dr i ver Manager . get Connect i on( " j dbc: mysql : / / l ocal host / t est " , " r oot " , " wxyz" ) ;
St at ement st mt =con. cr eat eSt at ement ( ) ;
St r i ng sql =" SELECT empno, ename, j ob, sal FROM Empl ; " ;
Resul t Set r s= st mt . execut eQuer y( sql ) ;
}
cat ch( Except i on e) { }
10 Following code is not printing all rows fetched from database. Figure out the problem.
class.forname("java.sql.Driver");
//Get a connection to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test",
"root", "wxyz");
// Get a statement from the connection
Statement stmt = conn.createStatement();
//Execute the query
ResultSet rs = stmt.executeQuery("SELECT * FROM Cust");
//Loop through the result set
while(rs.first())
System.out.println(rs.getString(1));
//close the result set, statement and the connection
rs.close();
stmt.close();
conn.close();
Ans. correct code:
cl ass. f or name( " j ava. sql . Dr i ver " ) ;
http://cbsecsnip.in



5
/ / Get a connect i on t o t he dat abase
Connect i on conn = Dr i ver Manager . get Connect i on( " j dbc: mysql : / / l ocal host / t est " ,
" r oot " , " wxyz" ) ;
/ / Get a st at ement f r omt he connect i on
St at ement st mt = conn. cr eat eSt at ement ( ) ;
/ / Execut e t he quer y
Resul t Set r s = st mt . execut eQuer y( " SELECT * FROM Cust " ) ;
/ / Loop t hr ough t he r esul t set
whi l e( r s. next( ) )
Syst em. out . pr i nt l n( r s. get St r i ng( 1) ) ;
Type C: Long Answer Questions
1 Design a GUI application that fetches all the records from Pet table of menagerie database.
Ans. i mpor t j ava. sql . *;
i mpor t j avax. swi ng. t abl e. *;
i mpor t j avax. swi ng. J Opt i onPane. *;
// Execute Button
Def aul t Tabl eModel model =( Def aul t Tabl eModel ) j Tabl e1. get Model ( ) ;
i nt r ows=model . get RowCount ( ) ;
i f ( r ows>0)
{
f or ( i nt i =0; i <r ows; i ++)
{
model . r emoveRow( 0) ;
}
}
St r i ng quer y=" sel ect * f r omPet " ;
t r y
{
Cl ass. f or Name( " com. mysql . j dbc. Dr i ver " ) ;
Connect i on
con=Dr i ver Manager . get Connect i on( " j dbc: mysql : / / l ocal host : 3306/ menager i e" , " r oot " ,
" " ) ;
St at ement smt =con. cr eat eSt at ement ( ) ;
Resul t Set r s=smt . execut eQuer y( quer y) ;
whi l e( r s. next ( ) )
{
i nt no=r s. get I nt ( " pet no" ) ;
St r i ng name=r s. get St r i ng( " name" ) ;
St r i ng t ype=r s. get St r i ng( " Type" ) ;
model . addRow( new Obj ect [ ] {no, name, t ype}) ;
}
}cat ch( Except i on e)
{ }

2 Design a GUI application that fetches only those records from Event table of menagerie database where type is
Kennel.
Ans. i mpor t j ava. sql . *;
i mpor t j avax. swi ng. t abl e. *;
http://cbsecsnip.in



6
i mpor t j avax. swi ng. J Opt i onPane. *;
// Execute button
Def aul t Tabl eModel model =( Def aul t Tabl eModel ) j Tabl e1. get Model ( ) ;
i nt r ows=model . get RowCount ( ) ;
i f ( r ows>0)
{
f or ( i nt i =0; i <r ows; i ++)
{
model . r emoveRow( 0) ;
}
}
St r i ng quer y=" sel ect * f r omEvent wher e t ype= Kennel ; ;
t r y
{
Cl ass. f or Name( " com. mysql . j dbc. Dr i ver " ) ;
Connect i on
con=Dr i ver Manager . get Connect i on( " j dbc: mysql : / / l ocal host : 3306/ menager i e" , " r oot " ,
" " ) ;
St at ement smt =con. cr eat eSt at ement ( ) ;
Resul t Set r s=smt . execut eQuer y( quer y) ;
whi l e( r s. next ( ) )
{
i nt no=r s. get I nt ( " Eno" ) ;
St r i ng name=r s. get St r i ng( " Ename" ) ;
St r i ng t ype=r s. get St r i ng( " Type" ) ;
model . addRow( new Obj ect [ ] {no, name, t ype}) ;
}
}cat ch( Except i on e)
{ }

3 Design a GUI application to obtain search criteria from user and then fetch records based on that from empl table.
Ans. i mpor t j ava. sql . *;
//Search button
i nt r no=I nt eger . par seI nt ( j Text Fi el d1. get Text ( ) ) ;
St r i ng quer y=" SELECT * FROM empl WHERE no=" + r no + " ; " ;
t r y{
Cl ass. f or Name( " com. mysql . j dbc. Dr i ver " ) ;
Connect i on
con=Dr i ver Manager . get Connect i on( " j dbc: mysql : / / l ocal host : 3306/ t est " , " r oot " , " " ) ;
St at ement st mt =con. cr eat eSt at ement ( ) ;
Resul t Set r s=st mt . execut eQuer y( quer y) ;
i f ( r s. next ( ) )
{
St r i ng sname=r s. get St r i ng( " name" ) ;
St r i ng add=r s. get St r i ng( " adr ess" ) ;
St r i ng cs=r s. get St r i ng( " t ype" ) ;
j Text Fi el d2. set Text ( sname) ;
j Text Fi el d3. set Text ( add) ;
j Text Fi el d4. set Text ( cs) ;
con. cl ose( ) ;
http://cbsecsnip.in



7
st mt . cl ose( ) ;
r s. cl ose( ) ;
}
el se
{
Syst em. out . pr i nt ( Recor d not f ound) ;
}
}
cat ch( Except i on e) {}




http://cbsecsnip.in

Você também pode gostar