![]() JDBC Interview Questions and Answers. Welcome to JDBC Interview Questions and Answers. JDBC API is used to connect to relational databases and run SQL queries from Java Programs. In last few articles, we learned about JDBC API and it’s important features. This article is aimed to provide some of the important JDBC Interview Questions with Answers to help you in Java interview. What is JDBC API and when do we use it? Java Data. Base Connectivity API allows us to work with relational databases. JDBC API interfaces and classes are part of java. We can use JDBC API to get the database connection, run SQL queries and stored procedures in the database server and process the results. JDBC API is written in a way to allow loose coupling between our Java program and actual JDBC drivers that makes our life easier in switching from one database to another database servers easily. What are different types of JDBC Drivers? ![]() There are four types of JDBC drivers. Any java program that works with database has two parts, first part is the JDBC API and second part is the driver that does the actual work. JDBC- ODBC Bridge plus ODBC Driver (Type 1): It uses ODBC driver to connect to database. We should have ODBC drivers installed to connect to database, that’s why this driver is almost obsolete. Native API partly Java technology- enabled driver (Type 2): This driver converts JDBC class to the client API for the database servers. We should have database client API installed. Because of extra dependency on database client API drivers, this is also not preferred driver. Pure Java Driver for Database Middleware (Type 3): This driver sends the JDBC calls to a middleware server that can connect to different type of databases. We should have a middleware server installed to work with this driver. This adds to extra network calls and slow performance and thats why not widely used JDBC driver. Direct- to- Database Pure Java Driver (Type 4): This driver converts the JDBC calls to the network protocol understood by the database server. This solution is simple and suitable for database connectivity over the network. However for this solution, we should use database specific drivers, for example OJDBC jars by Oracle for Oracle DB and My. SQL Connector/J for My. SQL databases. How does JDBC API helps us in achieving loose coupling between Java Program and JDBC Drivers API? JDBC API uses Java Reflection API to achieve loose coupling between java programs and JDBC Drivers. If you look at a simple JDBC example, you will notice that all the programming is done in terms of JDBC API and Driver comes in picture only when it’s loaded through reflection using Class. ![]() How do you connect to a MySQL database in Java? Here's a step by step explanation how to install MySQL and JDBC and how to use it. This JDBC Java tutorial describes how to use JDBC API to create, insert into, update, and query tables. You will also learn how to use simple and prepared statements. DeveloperWorks Data Db2 Db2 Community Share. Solve. Do more. Join the Db2 Community Watch the video Community Education Downloads Support Featured IBM Db2 Direct and. · · 5 FREE JAVA VIDEO COURSES - CLICK HERE - https://goo.gl/7i95F8 View more videos on my "Java JDBC Tutorial" Playlist: http:// Closed-Captioning. Name() method. I think this is one of the best example of using Reflection in core java classes to make sure that our application doesn’t work directly with Drivers API and that makes it very easy to move from one database to another. Please read more at JDBC Example. What is JDBC Connection? Explain steps to get Database connection in a simple java program. JDBC Connection is like a Session created with the database server. You can also think Connection is like a Socket connection from the database server. Creating a JDBC Connection is very easy and requires two steps: Register and Load the Driver: Using Class. Name(), Driver class is registered to the Driver. Manager and loaded in the memory. Use Driver. Manager to get the Connection object: We get connection object from Driver. Manager. get. Connection() by passing Database URL String, username and password as argument. Connection con = null. Driver Class. Class. Name("com. mysql. Driver"). // create the connection now. Driver. Manager. get. Connection("jdbc: mysql: //localhost: 3. User. DB". "pankaj. SQLException e) {. System. out. println("Check database is UP and configs are correct"). Stack. Trace(). }catch (Class. Not. Found. Exception e) {. System. out. println("Please include JDBC My. SQL jar in classpath"). Stack. Trace(). What is the use of JDBC Driver. Manager class? JDBC Driver. Manager is the factory class through which we get the Database Connection object. When we load the JDBC Driver class, it registers itself to the Driver. Manager, you can look up the JDBC Driver classes source code to check this. Then when we call Driver. Manager. get. Connection() method by passing the database configuration details, Driver. Manager uses the registered drivers to get the Connection and return it to the caller program. How to get the Database server details in java program? We can use Database. Meta. Data object to get the database server details. When the database connection is created successfully, we can get the meta data object by calling get. Meta. Data() method. There are so many methods in Database. Meta. Data that we can use to get the database product name, it’s version and configuration details. Database. Meta. Data meta. Data = con. get. Meta. Data(). String db. Product = meta. Data. Database. Product. Name(). What is JDBC Statement? JDBC API Statement is used to execute SQL queries in the database. We can create the Statement object by calling Connection create. Statement() method. We can use Statement to execute static SQL queries by passing query through different execute methods such as execute(), execute. Query(), execute. Update() etc. Since the query is generated in the java program, if the user input is not properly validated it can lead to SQL injection issue, more details can be found at SQL Injection Example. By default, only one Result. Set object per Statement object can be open at the same time. Therefore, if we want to work with multiple Result. Set objects, then each must have been generated by different Statement objects. All execute() methods in the Statement interface implicitly close a statment’s current Result. Set object if an open one exists. What is the difference between execute, execute. Query, execute. Update? Statement execute(String query) is used to execute any SQL query and it returns TRUE if the result is an Result. Set such as running Select queries. The output is FALSE when there is no Result. Set object such as running Insert or Update queries. We can use get. Result. Set() to get the Result. Set and get. Update. Count() method to retrieve the update count. Statement execute. Query(String query) is used to execute Select queries and returns the Result. Set. Result. Set returned is never null even if there are no records matching the query. When executing select queries we should use execute. Query method so that if someone tries to execute insert/update statement it will throw java. SQLException with message “execute. Query method can not be used for update”. Statement execute. Update(String query) is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0. You should use execute() method only when you are not sure about the type of statement else use execute. Query or execute. Update method. What is JDBC Prepared. Statement? JDBC Prepared. Statement object represents a precompiled SQL statement. We can use it’s setter method to set the variables for the query. Since Prepared. Statement is precompiled, it can then be used to efficiently execute this statement multiple times. Prepared. Statement is better choice that Statement because it automatically escapes the special characters and avoid SQL injection attacks. How to set NULL values in JDBC Prepared. Statement? We can use Prepared. Statement set. Null() method to bind the null variable to a parameter. The set. Null method takes index and SQL Types as argument, for exampleps. Null(1. 0, java. sql. Types. INTEGER). What is the use of get. Generated. Keys() method in Statement? Sometimes a table can have auto generated keys used to insert the unique column value for primary key. We can use Statement get. Generated. Keys() method to get the value of this auto generated key. What are the benefits of Prepared. Statement over Statement? Some of the benefits of Prepared. Statement over Statement are: Prepared. Statement helps us in preventing SQL injection attacks because it automatically escapes the special characters. Prepared. Statement allows us to execute dynamic queries with parameter inputs. Prepared. Statement is faster than Statement. It becomes more visible when we reuse the Prepared. Statement or use it’s batch processing methods for executing multiple queries. Java Database Connectivity - Wikipedia. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. It is Java based data access technology and used for Java database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation. It provides methods to query and update data in a database, and is oriented towards relational databases. A JDBC- to- ODBC bridge enables connections to any ODBC- accessible data source in the Java virtual machine (JVM) host environment. History and implementation[edit]Sun Microsystems released JDBC as part of Java Development Kit (JDK) 1. February 1. 9, 1. Since then it has been part of the Java Platform, Standard Edition (Java SE). The JDBC classes are contained in the Java packagejava. Starting with version 3. JDBC has been developed under the Java Community Process. JSR 5. 4 specifies JDBC 3. J2. SE 1. 4), JSR 1. JDBC Rowset additions, and JSR 2. JDBC 4. 0 (included in Java SE 6).[2]JDBC 4. JSR 2. 21[3] and is included in Java SE 7.[4]The latest version, JDBC 4. JSR 2. 21[5] and is included in Java SE 8.[6]JDBC 4. Java SE 9 in September 2. Specified by maintenance release 3 of JSR 2. Functionality[edit]JDBC allows multiple implementations to exist and be used by the same application. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating JDBC connections. JDBC connections support creating and executing statements. These may be update statements such as SQL's CREATE, INSERT, UPDATE and DELETE, or they may be query statements such as SELECT. Additionally, stored procedures may be invoked through a JDBC connection. JDBC represents statements using one of the following classes: Update statements such as INSERT, UPDATE and DELETE return an update count that indicates how many rows were affected in the database. These statements do not return any other information. Query statements return a JDBC row result set. The row result set is used to walk over the result set. Individual columns in a row are retrieved either by name or by column number. There may be any number of rows in the result set. The row result set has metadata that describes the names of the columns and their types. There is an extension to the basic JDBC API in the javax. JDBC connections are often managed via a connection pool rather than obtained directly from the driver. Examples[edit]When a Java application needs a database connection, one of the Driver. Manager. get. Connection() methods is used to create a JDBC connection. The URL used is dependent upon the particular database and JDBC driver. It will always begin with the "jdbc: " protocol, but the rest is up to the particular vendor. Connectionconn=Driver. Manager. get. Connection("jdbc: somejdbcvendor: other data needed by some jdbc vendor","my. Login","my. Password"); try{/* you use the connection here */}finally{//It's important to close the connection when you are done with ittry{conn. Throwablee){/* Propagate the original exceptioninstead of this one that you want just logged */logger. Could not close JDBC Connection",e); }}Starting from Java SE 7 you can use Java's try- with- resources statement to make the above code cleaner: try(Connectionconn=Driver. Manager. get. Connection("jdbc: somejdbcvendor: other data needed by some jdbc vendor","my. Login","my. Password")){/* you use the connection here */}// the VM will take care of closing the connection. Once a connection is established, a statement can be created. Statementstmt=conn. Statement()){stmt. Update("INSERT INTO My. Table( name ) VALUES ( 'my name' ) "); }Note that Connections, Statements, and Result. Sets often tie up operating system resources such as sockets or file descriptors. In the case of Connections to remote database servers, further resources are tied up on the server, e. Result. Sets. It is vital to close() any JDBC object as soon as it has played its part; garbage collection should not be relied upon. The above try- with- resources construct is a code pattern that obviates this. Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query. Statementstmt=conn. Statement(); Result. Setrs=stmt. execute. Query("SELECT * FROM My. Table")){while(rs. Columns=rs. get. Meta. Data(). get. Column. Count(); for(inti=1; i< =num. Columns; i++){// Column numbers start at 1.// Also there are many methods on the result set to return// the column as a particular type. Refer to the Sun documentation// for the list of valid conversions. System. out. println("COLUMN "+i+" = "+rs. Object(i)); }}}An example of a Prepared. Statement query, using conn and class from first example. Prepared. Statementps=conn. Statement("SELECT i.*, j.* FROM Omega i, Zappa j WHERE i. AND j. num = ?")){// In the SQL statement being prepared, each question mark is a placeholder// that must be replaced with a value you provide through a "set" method invocation.// The following two method calls replace the two placeholders; the first is// replaced by a string value, and the second by an integer value. String(1,"Poor Yorick"); ps. Int(2,8. 00. 8); // The Result. Set, rs, conveys the result of executing the SQL statement.// Each time you call rs. The cursor initially is// positioned before the first row. Result. Setrs=ps. Query()){while(rs. Columns=rs. get. Meta. Data(). get. Column. Count(); for(inti=1; i< =num. Columns; i++){// Column numbers start at 1.// Also there are many methods on the result set to return// the column as a particular type. Refer to the Sun documentation// for the list of valid conversions. System. out. println("COLUMN "+i+" = "+rs. Object(i)); }// for}// while}// try}// try. If a database operation fails, JDBC raises an SQLException. There is typically very little one can do to recover from such an error, apart from logging it with as much detail as possible. It is recommended that the SQLException be translated into an application domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user. An example of a database transaction: booleanauto. Commit. Default=conn. Auto. Commit(); try{conn. Auto. Commit(false); /* You execute statements against conn here transactionally */conn. Throwablee){try{conn. Throwablee){logger. Could not rollback transaction",e); }throwe; }finally{try{conn. Auto. Commit(auto. Commit. Default); }catch(Throwablee){logger. Could not restore Auto. Commit setting",e); }}Here are examples of host database types which Java can convert to with a function. XXX() Methods. Oracle Datatypeset. XXX()CHARset. String()VARCHAR2set. String()NUMBERset. Big. Decimal()set. Boolean()set. Byte()set. Short()set. Int()set. Long()set. Float()set. Double()INTEGERset. Int()FLOATset. Double()CLOBset. Clob()BLOBset. Blob()RAWset. Bytes()LONGRAWset. Bytes()DATEset. Date()set. Time()set. Timestamp()For an example of a Callable. Statement (to call stored procedures in the database), see the Java SE 8 documentation. Connection; importjava. Driver. Manager; importjava. Statement; publicclass. Mydb. 1{static. String. URL="jdbc: mysql: //localhost/mydb"; publicstaticvoidmain(String[]args){try{Class. Name("com. mysql. Driver"); Connectionconn=Driver. Manager. get. Connection(URL,"root","root"); Statementstmt=conn. Statement(); Stringsql="INSERT INTO emp. VALUES ('pctb. 53. Update(sql); System. Inserted records into the table.."); }catch(Exceptione){e. Stack. Trace(); }}}JDBC drivers[edit]JDBC drivers are client- side adapters (installed on the client machine, not on the server) that convert requests from Java programs to a protocol that the DBMS can understand. Commercial and free drivers provide connectivity to most relational- database servers. These drivers fall into one of the following types: Type 1 that calls native code of the locally available ODBC driver. Note: In JDBC 4. 2, JDBC- ODBC bridge has been removed[8])Type 2 that calls database vendor native library on a client side. This code then talks to database over the network. Type 3, the pure- java driver that talks with the server- side middleware that then talks to the database. Type 4, the pure- java driver that uses database native protocol. Note also a type called an internal JDBC driver - a driver embedded with JRE in Java- enabled SQL databases. It is used for Java stored procedures.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
November 2017
Categories |