web
 

JDBC Interview Questions and Answers


Welcome to JDBC Interview Questions and Answers. JDBC API is utilized to associate with social databases and run SQL questions from Java Programs. In the last couple of articles, we found out about JDBC API and its essential highlights. This article is intended to give a portion of the critical JDBC Interview Questions with Answers to help you in Java meet.

JDBC Interview Questions

What is JDBC API and when do we use it?
  • What are different types of JDBC Drivers?
  • How does JDBC API helps us in achieving loose coupling between Java Program and JDBC Drivers API?
  • What is JDBC Connection? Explain steps to get Database connection in a simple java program.
  • What is the use of JDBC DriverManager class?
  • How to get the Database server details in java program?
  • What is JDBC Statement?
  • What is the difference between execute, executeQuery, executeUpdate?
  • What is JDBC PreparedStatement?
  • How to set NULL values in JDBC PreparedStatement?
  • What is the use of getGeneratedKeys() method in Statement?
  • What are the benefits of PreparedStatement over Statement?
  • What is the limitation of PreparedStatement and how to overcome it?
  • What is JDBC ResultSet?
  • What are different types of ResultSet?
  • What is the use of setFetchSize() and setMaxRows() methods in Statement?
  • How to use JDBC API to call Stored Procedures?
  • What is JDBC Batch Processing and what are it’s benefits?
  • What is JDBC Transaction Management and why do we need it?
  • How to rollback a JDBC transaction?
  • What is JDBC Savepoint? How to use it?
  • What is JDBC DataSource and what are it’s benefits?
  • How to achieve JDBC Connection Pooling using JDBC DataSource and JNDI in Apache Tomcat Server?
  • What is Apache DBCP API?
  • What is JDBC Connection isolation levels?
  • What is JDBC RowSet? What are different types of RowSet?
  • What is the different between ResultSet and RowSet?
  • What are common JDBC Exceptions?
  • What is CLOB and BLOB datatypes in JDBC?
  • What is “dirty read” in JDBC? Which isolation level prevents dirty read?
  • What is 2 phase commit?
  • What are the different types of locking in JDBC?
  • What do you understand by DDL and DML statements?
  • What is difference between java.util.Date and java.sql.Date?
  • How to insert an image or raw data into database?
  • What is phantom read and which isolation level prevents it?
  • What is SQL Warning? How to retrieve SQL warnings in the JDBC program?
  • How to invoke Oracle Stored Procedure with Database Objects as IN/OUT?
  • When do we get java.sql.SQLException: No suitable driver found?
  • What are JDBC Best Practices?
  • JDBC Interview Questions and Answers

    1. What is JDBC API and when do we use it?

      Java DataBase Connectivity API allows us to work with relational databases. JDBC API interfaces and classes are part of java.sql and javax.sql package. 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 make 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.
    2. 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.
    3. 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.
    4. 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 MySQL Connector/J for MySQL 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.forName() method.

    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:

    1. Register and Load the Driver: Using Class.forName(), Driver class is registered to the DriverManager and loaded in the memory.
    2. Use DriverManager to get the Connection object: We get connection object from DriverManager.getConnection() by passing Database URL String, username and password as argument.
    3. Connection con = null; try{ // load the Driver Class Class.forName("com.mysql.jdbc.Driver"); // create the connection now con = DriverManager.getConnection("jdbc:mysql://localhost:3306/UserDB", "pankaj", "pankaj123"); }catch (SQLException e) { System.out.println("Check database is UP and configs are correct"); e.printStackTrace(); }catch (ClassNotFoundException e) { System.out.println("Please include JDBC MySQL jar in classpath"); e.printStackTrace(); }

      What is the use of JDBC DriverManager class?

      JDBC DriverManager is the factory class through which we get the Database Connection object. When we load the JDBC Driver class, it registers itself to the DriverManager, you can look up the JDBC Driver classes source code to check this.

      Then when we call DriverManager.getConnection() method by passing the database configuration details, DriverManager uses the registered drivers to get the Connection and return it to the caller program.

    4. How to get the Database server details in java program?

      We can use DatabaseMetaData object to get the database server details. When the database connection is created successfully, we can get the meta data object by calling getMetaData() method. There are so many methods in DatabaseMetaData that we can use to get the database product name, it’s version and configuration details.

      DatabaseMetaData metaData = con.getMetaData(); String dbProduct = metaData.getDatabaseProductName();

      What is JDBC Statement?

      JDBC API Statement is utilized to execute SQL questions in the database. We can make the Statement object by calling Connection createStatement() strategy. We can utilize Statement to execute static SQL inquiries by going inquiry through various execute techniques, for example, execute(), executeQuery(), executeUpdate() etc.

      As a matter of course, one and only ResultSet object per Statement article can be open in the meantime. In this way, on the off chance that we need to work with various ResultSet objects, at that point each more likely than not been produced by various Statement objects. All execute() techniques in the Statement interface certainly close a statment's present ResultSet object if an open one exists.

      What is the contrast between execute, executeQuery, executeUpdate?

      Statement execute(String query) is utilized to execute any SQL question and it returns TRUE if the outcome is a ResultSet, for example, running Select inquiries. The yield is FALSE when there is no ResultSet article, for example, running Insert or Update questions. We can utilize getResultSet() to get the ResultSet and getUpdateCount() strategy to recover the update count.

      Statement executeQuery(String query) is utilized to execute Select questions and returns the ResultSet.

      ResultSet returned is never invalid regardless of whether there are no records coordinating the inquiry. When executing select questions we should utilize the executeQuery strategy so that on the off chance that somebody endeavors to execute embed/update proclamation it will toss java.sql.SQLException with message "executeQuery technique can't be utilized for update".

      Statement executeUpdate(String inquiry) is utilized to execute Insert/Update/Delete (DML) explanations or DDL articulations that profits nothing. The yield is int and equivalents the column mean SQL Data Manipulation Language (DML) explanations. For DDL proclamations, the yield is 0.

      You should utilize execute() strategy just when you don't know about the sort of articulation else use executeQuery or executeUpdate method.

    5. What is JDBC PreparedStatement?

      JDBC PreparedStatement object speaks to a precompiled SQL explanation. We can utilize it's setter technique to set the factors for the query.

      Since PreparedStatement is precompiled, it would then be able to be utilized to proficiently execute this announcement on numerous occasions. PreparedStatement is better decision that Statement since it naturally gets away from the extraordinary characters and maintain a strategic distance from SQL infusion attacks.

    6. How to set NULL qualities in JDBC PreparedStatement?

      We can utilize PreparedStatement setNull() strategy to tie the invalid variable to a parameter. The setNull strategy takes record and SQL Types as contention, for example
      ps.setNull(10, java.sql.Types.INTEGER);.

    7. What is the utilization of getGeneratedKeys() strategy in Statement?

      Sometimes a table can have auto produced keys used to embed the exceptional section an incentive for essential key. We can utilize Statement getGeneratedKeys() technique to get the estimation of this auto created key.

      What are the advantages of PreparedStatement over Statement?

      Some of the advantages of PreparedStatement over Statement are:

      • PreparedStatement encourages us in averting SQL infusion assaults since it consequently gets away from the extraordinary characters.
      • PreparedStatement enables us to execute dynamic questions with parameter inputs.
      • PreparedStatement is quicker than Statement. It turns out to be progressively unmistakable when we reuse the PreparedStatement or utilize it's group handling strategies for executing numerous queries.
      • PreparedStatement causes us recorded as a hard copy object Oriented code with setter techniques though with Statement we need to utilize String Concatenation to make the inquiry. On the off chance that there are numerous parameters to set, composing Query utilizing String link looks in all respects terrible and mistake prone.
    8. What is the impediment of PreparedStatement and how to defeat it?

      One of the confinement of PreparedStatement is that we can't utilize it legitimately with IN condition proclamations. A portion of the elective ways to deal with use PreparedStatement with IN condition are;

      1. Execute Single Queries – moderate execution and not recommended
      2. Using Stored Procedure – Database explicit and henceforth not appropriate for numerous database applications.
      3. Creating PreparedStatement Query dynamically – Good methodology yet looses the advantage of reserved PreparedStatement.
      4. Using NULL in PreparedStatement Query – A great methodology when you know the most extreme number of factors inputs, can be reached out to permit boundless parameters by executing in parts.
      5. What is JDBC ResultSet?

        JDBC ResultSet resembles a table of information speaking to a database result set, which is generally created by executing an explanation that questions the database.

        ResultSet object keeps up a cursor indicating its present line of information. At first, the cursor is situated before the primary column. The following() technique moves the cursor to the following column. In the event that there are no more lines, next() strategy returns false and it very well may be utilized in some time circle to repeat through the outcome set.

        A default ResultSet object isn't updatable and has a cursor that pushes ahead as it were. Hence, you can repeat through it just once and just from the principal column to the last line. It is conceivable to deliver ResultSet objects that are scrollable

        A ResultSet object is naturally shut when the Statement object that produced it is shut, re-executed, or used to recover the following outcome from an arrangement of numerous results.

        We can utilize ResultSet getter technique with segment name or list number beginning from 1 to recover the segment data.

      6. What are diverse kinds of ResultSet?

        There are distinctive sorts of ResultSet objects that we can get dependent on the client input while making the Statement. In the event that you will investigate the Connection techniques, you will see that createStatement() and prepareStatement() strategy are over-burden to give ResultSet type

        There are three sorts of ResultSet object.

        1. ResultSet.TYPE_FORWARD_ONLY: This is the default type and cursor can just push ahead in the outcome set.
        2. ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can push ahead and in reverse, and the outcome set isn't touchy to changes made by others to the database after the outcome set was created.
        3. ResultSet.TYPE_SCROLL_SENSITIVE: The cursor can push ahead and in reverse, and the outcome set is delicate to changes made by others to the database after the outcome set was created.

        Based on the simultaneousness there are two kinds of ResultSet object.

        1. ResultSet.CONCUR_READ_ONLY: The outcome set is perused just, this is the default simultaneousness type.
        2. ResultSet.CONCUR_UPDATABLE: We can utilize ResultSet update technique to refresh the lines data.
      7. What is the utilization of setFetchSize() and setMaxRows() strategies in Statement?

        Understanding fetchSize can be dubious, for that you should know how Statement and ResultSet functions. When we execute a question in the database, the outcome is acquired and kept up in the database reserve and ResultSet is returned. ResultSet is the cursor that has the reference to the outcome in the database.

        Let's state we have a question that profits 100 lines and we have set fetchSize to 10, so in each database trip JDBC driver will bring just 10 columns and subsequently there will be 10 treks to bring every one of the lines. Setting ideal fetchSize is useful when you need a great deal of preparing time for each line and number of columns in the outcome is huge.

        We can set fetchSize through Statement object yet it tends to be abrogated through ResultSet object setFetchSize() method.

      8. How to utilize JDBC API to call Stored Procedures?

        Stored Procedures are gathering of SQL questions that are incorporated in the database and can be executed from JDBC API. JDBC CallableStatement can be utilized to execute put away techniques in the database. The sentence structure to instate CallableStatement is;

         
        
        CallableStatement stmt = con.prepareCall("{call insertEmployee(?,?,?,?,?,?)}"); 
        
        stmt.setInt(1, id); 
        
        stmt.setString(2, name); 
        
        stmt.setString(3, job); 
        
        stmt.setString(4, city); 
        
        stmt.setString(5, nation); 
        
        //register the OUT parameter before calling the put away procedure 
        
        stmt.registerOutParameter(6, java.sql.Types.VARCHAR); 
        
        stmt.executeUpdate(); 
        
        

        What is JDBC Batch Processing and what are it's benefits?

        Sometimes we have to run mass questions of a comparative kind for a database. For instance, stacking information from CSV documents to social database tables. As we realize that we have the alternative to utilize Statement or PreparedStatement to execute questions. Aside from that JDBC API gives Batch Processing highlight through which we can execute the majority of questions in one go for a database.

        JDBC API underpins bunch handling through Statement and PreparedStatement addBatch() and executeBatch() methods.

        What is JDBC Transaction Management and for what reason do we need it?

        By default when we make a database association, it keeps running in auto-submit mode. It implies that at whatever point we execute an inquiry and it's finished, the submit is terminated consequently. So every SQL question we fire is an exchange and in the event that we are running some DML or DDL inquiries, the progressions are getting spared into the database after each SQL proclamation finishes.

        Sometimes we need a gathering of SQL questions to be a piece of an exchange with the goal that we can submit them when every one of the questions run fine and in the event that we get a special case, we have a decision of rollback every one of the questions executed as a component of the transaction.

        JDBC API give strategy setAutoCommit(boolean flag) through which we can cripple the auto submit highlight of the association. We should cripple auto submit just when it's required in light of the fact that the exchange won't be submitted except if we call the submit() strategy on association. Database servers utilizes table locks to accomplish exchange the board and it's asset escalated process. So we ought to submit the exchange when we are finished with it.

        How to rollback a JDBC transaction?

        We can utilize Connection object rollback() technique to rollback the exchange. It will rollback every one of the progressions made by the exchange and discharge any database bolts at present held by this Connection object.

      9. What is JDBC Savepoint? Step by step instructions to utilize it?

        Sometimes an exchange can be gathering of numerous announcements and we might want to rollback to a specific point in the exchange. JDBC Savepoint encourages us in making checkpoints in an exchange and we can rollback to that specific checkpoint.

        Any savepoint made for an exchange is consequently discharged and turned out to be invalid when the exchange is submitted, or when the whole exchange is moved back. Rolling an exchange back to a savepoint consequently discharges and makes invalid some other savepoints that were made after the savepoint being referred to

        How to accomplish JDBC Connection Pooling utilizing JDBC DataSource and JNDI in Apache Tomcat Server?

        For web applications conveyed in a servlet holder, making JDBC association pool is simple and include just few steps.

        1. Creating JDBC JNDI asset in the compartment setup documents, typically server.xml or context.xml. For example

          server.xmlFor example

          server.xml

           
          
          <Resource name="jdbc/MyDB" 
          
          global="jdbc/MyDB" 
          
          auth="Container" 
          
          type="javax.sql.DataSource" 
          
          driverClassName="com.mysql.jdbc.Driver" 
          
          url="jdbc:mysql://localhost:3306/UserDB" 
          
          username="pankaj" 
          
          password="pankaj123" 
          
          maxActive="100" 
          
          maxIdle="20" 
          
          minIdle="5" 
          
          maxWait="10000"/> 
          
          

          context.xml

           
          
          <ResourceLink name="jdbc/MyLocalDB" 
          
          global="jdbc/MyDB" 
          
          auth="Container" 
          
          type="javax.sql.DataSource"/> 
          
          
        2. In web application, utilizing InitialContext to look into the JNDI asset designed in the initial step and after that get the connection.
           
          
          Setting ctx = new InitialContext(); 
          
          DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/MyLocalDB"); 
          
          

          What is Apache DBCP API?

          If you use DataSource to get the Database association, for the most part the code to get the association is firmly combined with the Driver explicit DataSource execution. Additionally the vast majority of the code is standard code with the exception of the decision of the DataSource usage class.

          Apache DBCP causes us in disposing of these issues by giving DataSource execution that fills in as a deliberation layer between our program and diverse JDBC drivers. Apache DBCP library relies upon Commons Pool library, so ensure they both are in the assemble path.

          What is JDBC RowSet? What are diverse sorts of RowSet?

          JDBC RowSet holds unthinkable information in increasingly adaptable ways that ResultSet. All RowSet objects are gotten from ResultSet, so they have every one of the capacities of ResultSet with some extra highlights. RowSet interface is characterized in javax.sql package.

          Some extra highlights given by RowSet are:

          • Functions as Java Beans with properties and their getter-setter strategies. RowSet utilizes JavaBeans occasion model and they can send warnings to any enlisted segment for occasions, for example, cursor development, update/embed/erase of a column and change to RowSet contents.
          • RowSet objects are scrollable and updatable of course, so if DBMS doesn't bolster scrollable or updatable ResultSet, we can utilize RowSet to get these features.

          RowSet are comprehensively separated into two types:

          1. Connected RowSet Objects – These articles are associated with database and are most like ResultSet object. JDBC API gives just a single associated RowSet object javax.sql.rowset.JdbcRowSet and it's standard execution class is com.sun.rowset.JdbcRowSetImpl
          2. Disconnected RowSet Objects – These RowSet objects are not required to associated with a database, so they are progressively lightweight and serializable. They are reasonable for sending information over a system. There are four kinds of disengaged RowSet implementations.
            • CachedRowSet – They can get the association and execute a question and read the ResultSet information to populate the RowSet information. We can control and refresh information while it is separated and reconnect to database and compose the changes.
            • WebRowSet got from CachedRowSet – They can peruse and compose XML document.
            • JoinRowSet got from WebRowSet – They can frame SQL JOIN without interfacing with an information source.
            • FilteredRowSet got from WebRowSet – We can apply sifting criteria so just chosen information is visible.
        3. What is the diverse among ResultSet and RowSet?

          RowSet objects are gotten from ResultSet, so they have every one of the highlights of ResultSet with some extra highlights. One of the colossal advantage of RowSet is that they can be detached and that makes it lightweight and simple to exchange over a network.

          Whether to utilize ResultSet or RowSet relies upon your prerequisites however on the off chance that you are intending to utilize ResultSet for longer length, at that point a separated RowSet is better decision to free database resources.

        4. What are basic JDBC Exceptions?

          Some of the basic JDBC Exceptions are:

          1. java.sql.SQLException – This is the base exemption class for JDBC exceptions.
          2. java.sql.BatchUpdateException – This special case is tossed when Batch task flops, yet it relies upon the JDBC driver whether they toss this exemption or the base SQLException.
          3. java.sql.SQLWarning – For notice messages in SQL operations.
          4. java.sql.DataTruncation – when an information esteems is out of the blue truncated for reasons other than its having surpassed MaxFieldSize.
          5. What is CLOB and BLOB datatypes in JDBC?

            Character Large OBjects (CLOBs) are character string comprised of single-byte characters with a related code page. This information type is fitting for putting away content arranged data where the measure of data can develop past the points of confinement of a customary VARCHAR information type (furthest farthest point of 32K bytes).

            Binary Large Objects (BLOBs) are a parallel string comprised of bytes with no related code page. This information type can store parallel information bigger than VARBINARY (32K breaking point). This information type is useful for putting away picture, voice, graphical, and different kinds of business or application-explicit data.

          6. What is "messy perused" in JDBC? Which confinement level averts filthy read?

            When we work with exchanges, quite possibly a column is refreshed and in the meantime, another inquiry can peruse the refreshed esteem. This outcomes in a filthy read in light of the fact that the refreshed esteem isn't lasting yet, the exchange that has refreshed the line can rollback to a past esteem bringing about invalid data.

            Dirty Read is anticipated by detachment levels TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, and TRANSACTION_SERIALIZABLE.

          7. What is 2 stage commit?

            When we work in disseminated frameworks where numerous databases are included, we are required to utilize 2 stage submit convention. 2 stage submit convention is a nuclear responsibility convention for circulated frameworks. In the main stage, the exchange director sends submit solicitation to all the exchange assets. In the event that all the exchange assets are OK, the exchange administrator submits the exchange changes for every one of the assets. In the event that any of the exchange assets reacts as Abort, at that point the exchange administrator can rollback all the exchange changes.

            What are the distinctive sorts of securing JDBC?

            On an expansive dimension, there are two kinds of locking instrument to anticipate information debasement as a result of more than one client working with the equivalent data.

            1. Optimistic Locking – This locking is accomplished with code. An additional section is acquainted in the table with keep a check of updates. When you select the line, you read this section as well, say 'form'. Presently when you are endeavoring to refresh/erase the column, you pass this 'form' in the where proviso. So if there are refreshes from different strings performed in the middle of, the update will fall flat. It's a decent method to maintain a strategic distance from information defilement however it very well may be mistake inclined on the off chance that somebody missed refreshing the 'variant' in their update articulation. The update inquiry looks something prefer beneath in as such of locking. Pessimistic Locking – Locking the record from the select to read, update and commit phase. This is usually done by database vendor software and triggered by the use of SELECT FOR UPDATE query. This way of locking the row can lead to slow performance and deadlock if threads are handling the lock for longer time.

            Apart from that some DBMS systems provide locking mechanism to lock single row, table or database.

          8. What do you understand by DDL and DML statements?

            Data Definition Language (DDL) statements are used to define the database schema. Create, Alter, Drop, Truncate, Rename statements comes under DDL statements and usually they don’t return any result.

            Data Manipulation Language (DML) statements are used to manipulate data in the database schema. Select, Insert, Update, Delete, Call etc are example of DML statements.

            What is contrast among java.util.Date and java.sql.Date?

            java.util.Date contains data about the date and time while java.sql.Date contains data just about the date, it doesn't have time data. So on the off chance that you need to keep time data in the database, it is fitting to utilize Timestamp or DateTime fields.

          9. How to embed a picture or crude information into database?

            We can utilize BLOB to embed picture or crude double information into database.

          10. What is apparition perused and which segregation level avoids it?

            A ghost read is where an exchange executes an inquiry on various occasions and get diverse information. Assume an exchange is executing an inquiry to get information dependent on a condition and after that another exchange embeds a column that coordinates the condition. Presently when same exchange will execute the inquiry once more, another line will be a piece of the outcome set. This new line is alluded as Phantom Row and this circumstance is named as Phantom Read.

            Phantom perused can be avoided just with TRANSACTION_SERIALIZABLE disengagement level.

          11. What is SQL Warning? Instructions to recover SQL alerts in the JDBC program?

            SQLWarning is the subclass of SQLException and we can recover it by calling getWarnings() technique on Connection, Statement, and ResultSet objects. SQL Warnings doesn't stop the execution of the content however alarms the client about the warning.

          12. How to conjure Oracle Stored Procedure with Database Objects as IN/OUT?

            If Oracle Stored Procedure has IN/OUT parameters as DB Objects then we have to make an Object cluster of a similar size in the program and afterward use it to make Oracle STRUCT object. At that point we can set this STRUCT object for the database object by calling setSTRUCT() technique and work with it.

            When do we get java.sql.SQLException: No reasonable driver found?

            You get No appropriate driver discovered special case when the SQL URL String isn't legitimately organized. You can get this exemption in both basic java application utilizing DriverManager or with JNDI asset utilizing DataSource. The special case stack follow looks like below.

             
            
            org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL ''jdbc:mysql://localhost:3306/UserDB' 
            
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452) 
            
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371) 
            
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) 
            
            java.sql.SQLException: No reasonable driver found for 'jdbc:mysql://localhost:3306/UserDB 
            
            at java.sql.DriverManager.getConnection(DriverManager.java:604) 
            
            at java.sql.DriverManager.getConnection(DriverManager.java:221) 
            
            at com.journaldev.jdbc.DBConnection.getConnection(DBConnection.java:24) 
            
            at com.journaldev.jdbc.DBConnectionTest.main(DBConnectionTest.java:15) 
            
            Exception in thread "main" java.lang.NullPointerException 
            
            at com.journaldev.jdbc.DBConnectionTest.main(DBConnectionTest.java:16) 
            
            

            While investigating this special case, simply check the URL getting imprinted in the logs, as in above logs the URL String seems to be 'jdbc:mysql://localhost:3306/UserDB while it ought to be jdbc:mysql://localhost:3306/UserDB.

          13. What are JDBC Best Practices?

            Some of the JDBC Best Practices are:

            • Database assets are substantial, so ensure you close it when you are finished with it. Association, Statement, ResultSet and all other JDBC objects have close() technique characterized to close them.
            • Always close the outcome set, explanation and association expressly in the code, in such a case that you are working in association pooling condition, the association may be come back to the pool leaving open outcome sets and articulation objects bringing about asset leak.
            • Close the assets in the at last square to ensure they are shut even if there should be an occurrence of special case scenarios.
            • Use bunch handling for mass activities of comparable kind.
            • Always use PreparedStatement over Statement to stay away from SQL Injection and get pre-aggregation and storing advantages of PreparedStatement.
            • If you are recovering mass information into result set, setting an ideal incentive for fetchSize helps in getting great performance.
            • The database server probably won't bolster all detachment levels, so check it before assuming.
            • More exacting disengagement levels result in moderate execution, so ensure you have ideal confinement level set for your database connections.
            • If you are making database associations in a web application, attempt to utilize JDBC DataSource assets utilizing JNDI setting for re-utilizing the connections.
            • Try to utilize separated RowSet when you have to work with ResultSet for a long time.
            • That’s all for JDBC interview questions and answers, I hope it will help you in JDBC interviews. Let me know if I have missed any important question and I will add it to the list.





  • journaldev is optimized for learning.© journaldev .
    All Right Reserved and you agree to have read and accepted our term and condition