• Home
  • Privacy Policy
Breaking News, US News, World News and Bollywood News
  • Home
  • Technology
    Top technologists have job options: 5 tips for retention

    Top technologists have job options: 5 tips for retention

    CNCF launches ethics in open source training course

    CNCF launches ethics in open source training course

    More money for open source security won’t work

    More money for open source security won’t work

    Review: YugabyteDB does PostgreSQL proud

    Review: YugabyteDB does PostgreSQL proud

    Microsoft .NET 7 Preview 1 coming this week

    Microsoft .NET 7 Preview 4 brings Regex improvements, cache metrics

    Does your deployed infrastructure match what you defined?

    Do your AWS deployments match your Terraform definitions? Use SQL to find out.

    Trending Tags

    • Nintendo Switch
    • CES 2017
    • Playstation 4 Pro
    • Mark Zuckerberg
  • Entertainment
    The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

    The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

    Wordle 332 May 17 HINTS – Struggling with today’s Wordle? Three clues to help with answer | Gaming | Entertainment

    Wordle 332 May 17 HINTS – Struggling with today’s Wordle? Three clues to help with answer | Gaming | Entertainment

    Fortnite update 20.40 patch notes, downtime, Obi-Wan launch, PlayStation V-bucks and MORE | Gaming | Entertainment

    Fortnite update 20.40 patch notes, downtime, Obi-Wan launch, PlayStation V-bucks and MORE | Gaming | Entertainment

    Pirates of the Caribbean 6: Hope for Johnny Depp Jack Sparrow return shared by producer | Films | Entertainment

    Pirates of the Caribbean 6: Hope for Johnny Depp Jack Sparrow return shared by producer | Films | Entertainment

    Captain America 4 ‘sees Moon Knight team up against Secret Empire’ Chris Evans HYDRA Cap? | Films | Entertainment

    Captain America 4 ‘sees Moon Knight team up against Secret Empire’ Chris Evans HYDRA Cap? | Films | Entertainment

    Chainsaw Man anime release date: Crunchyroll streams hit anime in 2022 | Gaming | Entertainment

    Chainsaw Man anime release date: Crunchyroll streams hit anime in 2022 | Gaming | Entertainment

    Trending Tags

      • Bollywood
      • Hollywood
      • Music
    • Lifestyle
      When to plant courgettes outside – the ‘safest’ time when ‘risk of frost has passed’

      When to plant courgettes outside – the ‘safest’ time when ‘risk of frost has passed’

      How to kill weeds without harming grass – 4 best ways to get rid of weeds and ingredients

      How to kill weeds without harming grass – 4 best ways to get rid of weeds and ingredients

      Garden furniture: Key thing to look out for when buying rattan

      Garden furniture: Key thing to look out for when buying rattan

      Aloe vera: ‘Best tip’ when repotting houseplant to give it ‘conditions it enjoys most’

      Aloe vera: ‘Best tip’ when repotting houseplant to give it ‘conditions it enjoys most’

      Lawn care: What to remember when mowing lawn for ‘lush and healthy grass’

      Lawn care: What to remember when mowing lawn for ‘lush and healthy grass’

      Tomatoes: How to ‘boost fruiting’ and produce ‘plenty of delicious tomatoes’ – care tips

      Tomatoes: How to ‘boost fruiting’ and produce ‘plenty of delicious tomatoes’ – care tips

      Trending Tags

      • Golden Globes
      • Game of Thrones
      • MotoGP 2017
      • eSports
      • Fashion Week
    • Nature
    • Business
    • Health
      • Food
    • Fashion
    • Science
    • Sports
    • Travel
    • World News
    No Result
    View All Result
    • Home
    • Technology
      Top technologists have job options: 5 tips for retention

      Top technologists have job options: 5 tips for retention

      CNCF launches ethics in open source training course

      CNCF launches ethics in open source training course

      More money for open source security won’t work

      More money for open source security won’t work

      Review: YugabyteDB does PostgreSQL proud

      Review: YugabyteDB does PostgreSQL proud

      Microsoft .NET 7 Preview 1 coming this week

      Microsoft .NET 7 Preview 4 brings Regex improvements, cache metrics

      Does your deployed infrastructure match what you defined?

      Do your AWS deployments match your Terraform definitions? Use SQL to find out.

      Trending Tags

      • Nintendo Switch
      • CES 2017
      • Playstation 4 Pro
      • Mark Zuckerberg
    • Entertainment
      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      Wordle 332 May 17 HINTS – Struggling with today’s Wordle? Three clues to help with answer | Gaming | Entertainment

      Wordle 332 May 17 HINTS – Struggling with today’s Wordle? Three clues to help with answer | Gaming | Entertainment

      Fortnite update 20.40 patch notes, downtime, Obi-Wan launch, PlayStation V-bucks and MORE | Gaming | Entertainment

      Fortnite update 20.40 patch notes, downtime, Obi-Wan launch, PlayStation V-bucks and MORE | Gaming | Entertainment

      Pirates of the Caribbean 6: Hope for Johnny Depp Jack Sparrow return shared by producer | Films | Entertainment

      Pirates of the Caribbean 6: Hope for Johnny Depp Jack Sparrow return shared by producer | Films | Entertainment

      Captain America 4 ‘sees Moon Knight team up against Secret Empire’ Chris Evans HYDRA Cap? | Films | Entertainment

      Captain America 4 ‘sees Moon Knight team up against Secret Empire’ Chris Evans HYDRA Cap? | Films | Entertainment

      Chainsaw Man anime release date: Crunchyroll streams hit anime in 2022 | Gaming | Entertainment

      Chainsaw Man anime release date: Crunchyroll streams hit anime in 2022 | Gaming | Entertainment

      Trending Tags

        • Bollywood
        • Hollywood
        • Music
      • Lifestyle
        When to plant courgettes outside – the ‘safest’ time when ‘risk of frost has passed’

        When to plant courgettes outside – the ‘safest’ time when ‘risk of frost has passed’

        How to kill weeds without harming grass – 4 best ways to get rid of weeds and ingredients

        How to kill weeds without harming grass – 4 best ways to get rid of weeds and ingredients

        Garden furniture: Key thing to look out for when buying rattan

        Garden furniture: Key thing to look out for when buying rattan

        Aloe vera: ‘Best tip’ when repotting houseplant to give it ‘conditions it enjoys most’

        Aloe vera: ‘Best tip’ when repotting houseplant to give it ‘conditions it enjoys most’

        Lawn care: What to remember when mowing lawn for ‘lush and healthy grass’

        Lawn care: What to remember when mowing lawn for ‘lush and healthy grass’

        Tomatoes: How to ‘boost fruiting’ and produce ‘plenty of delicious tomatoes’ – care tips

        Tomatoes: How to ‘boost fruiting’ and produce ‘plenty of delicious tomatoes’ – care tips

        Trending Tags

        • Golden Globes
        • Game of Thrones
        • MotoGP 2017
        • eSports
        • Fashion Week
      • Nature
      • Business
      • Health
        • Food
      • Fashion
      • Science
      • Sports
      • Travel
      • World News
      No Result
      View All Result
      Updates News
      No Result
      View All Result
      Home Technology

      What is JDBC? Introduction to Java Database Connectivity

      admin by admin
      May 13, 2022
      in Technology
      0
      What is JDBC? Introduction to Java Database Connectivity
      0
      SHARES
      3
      VIEWS
      Share on FacebookShare on Twitter


      JDBC (Java Database Connectivity) is the Java API that manages connecting to a database, issuing queries and commands, and handling result sets obtained from the database. Released as part of JDK 1.1 in 1997, JDBC was one of the earliest libraries developed for the Java language.

      JDBC was initially conceived as a client-side API, enabling a Java client to interact with a data source. That changed with JDBC 2.0, which included an optional package supporting server-side JDBC connections. Every new JDBC release since then has featured updates to both the client-side package (java.sql) and the server-side package (javax.sql). JDBC 4.3, the most current version as of this writing, was released as part of Java SE 9 in September 2017 as JSR 221.

      This article presents an overview of JDBC and JDBC drivers, followed by a hands-on introduction to using JDBC to connect a Java client to a lightweight relational database.

      How JDBC works

      As a developer, you can use JDBC to interact with a database from within a Java program. JDBC acts as a bridge from your code to the database, as shown in Figure 1.

      JDBC connects Java programs to databases. IDG

      Figure 1. JDBC connects Java programs to databases.

      JDBC vs ODBC

      Before JDBC, developers used Open Database Connectivity (ODBC), a language-agnostic standard approach to accessing a relational database management system, or RDBMS. In some ways, JDBC takes its inspiration from ODBC. The difference is that JDBC is Java-specific, offering a programming-level interface that handles the mechanics of Java applications communicating with a database.

      JDBC’s architecture

      The JDBC interface consists of two layers:

      1. The JDBC API supports communication between the Java application and the JDBC manager.
      2. The JDBC driver supports communication between the JDBC manager and the database driver.

      The JDBC API and JDBC driver have been refined extensively over the years, resulting in a feature-rich, performant, and reliable library.

      JDBC is the common API that your application code interacts with. Beneath that is the JDBC-compliant driver for the database you are using.

      Figure 2 illustrates the JDBC architecture.

      The JDBC interface consists of the JDBC API and its drivers. IDG

      Figure 2. JDBC’s architecture consists of the JDBC API and JDBC drivers.

      JDBC drivers

      As an application programmer, you don’t need to immediately be concerned with the implementation of the driver you use, so long as it is secure and official. However, it is useful to be aware that there are four JDBC driver types:

      1. JDBC-ODBC bridge driver: A thin Java layer that uses an ODBC driver under the hood.
      2. Native API driver: Provides an interface from Java to the native database client.
      3. Middleware driver: A universal interface (“middleware”) between Java and the RDBMS’s vendor-specific protocol.
      4. Pure Java driver: A driver that implements the vendor-specific protocol directly in Java.

      When you start thinking about architecture and performance, it will be beneficial to consider the type of driver you are using.

      Simple database connections and queries

      One of the benefits of programming in the Java ecosystem is that you will likely find a stable JDBC database connector for whatever database you choose. In this tutorial, we’ll use SQLite to get to know JDBC, mainly because it’s so easy to use.

      The steps for connecting to a database with JDBC are as follows:

      1. Install or locate the database you want to access.
      2. Include the JDBC library.
      3. Ensure the JDBC driver you need is on your classpath.
      4. Use the JDBC library to obtain a connection to the database.
      5. Use the connection to issue SQL commands.
      6. Close the connection when you are finished.

      We’ll go through these steps together.

      Step 1. Download and install SQLite

      SQLite is a very compact database. It isn’t intended for production use but is a great choice for quickly trying things out. SQLite uses a file as its functional database, without requiring any service or daemon installations.

      To get started with this demonstration, first download the SQLite sample database. Unzip the .db file and save it somewhere you won’t forget. This file contains both a functional file-based database and sample schema and data that we can use.

      Step 2. Import JDBC into your Java application

      We could do our coding in an IDE, but coding directly in a text editor will better demonstrate JDBC’s simplicity. To begin, you will need to have a compatible JDK installation for your operating system.

      Assuming you have a JDK installed, we can start by creating a simple Java program. In your text editor, paste in the code shown in Listing 1. Call this file WhatIsJdbc.java.

      Listing 1. A simple Java program

      
      class WhatIsJdbc{
        public static void main(String args[]){
            System.out.println("Hello InfoWorld");
        }
      }
      

      Now, compile the code by entering the command: javac WhatIsJdbc.java. Compiling will output the WhatIsJdbc.class file. Execute this file from the command line with the call: java WhatIsJdbc.

      Once you have a basic Java program, you can include the JDBC libraries. Paste in the code from Listing 2 at the head of your simple Java program.

      Listing 2. JDBC imports

      
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      import java.sql.ResultSet;
      import java.sql.Statement;
      

      Each of these imports provides access to a class that facilitates the standard Java database connection:

      • Connection represents the connection to the database.
      • DriverManager obtains the connection to the database. (Another option is DataSource, used for connection pooling.)
      • SQLException handles SQL errors between the Java application and the database.
      • ResultSet and Statement model the data result sets and SQL statements.

      You’ll see each of these in action shortly.

      Step 3. Add the JDBC driver to your classpath

      Next, you’ll add the SQLite driver to your classpath. Remember, a JDBC driver is a class that implements the JDBC API for a specific database.

      Go to the GitHub page for SQLite driver and download the latest SQLite .jar. If you are using Maven or Gradle, or something similar, you can add the driver via the Maven repository. Be sure to get the most recent .jar file and store it somewhere you’ll remember.

      The next time you execute your Java program, you will pull in that .jar file via the classpath. There are several ways to set the classpath. Listing 3 shows how to do it using a command-line switch.

      Listing 3. Executing the SQLite driver on the Java classpath

      
      java.exe -classpath /path-to-driver/sqlite-jdbc-3.23.1.jar:. WhatIsJdbc
      

      Notice that we’ve set the classpath to point at the driver and the local directory; this way, Java will still find our class file.

      Step 4. Obtain a database connection

      The classpath now has access to the driver. Next, change your simple Java application file to look like the program in Listing 4.

      Listing 4. Using the JDBC Connection class to connect to SQLite

      
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      import java.sql.ResultSet;
      import java.sql.Statement;
      
       String sql = "SELECT id, username FROM users WHERE id = ?";
          List users = new ArrayList<>();
          try (Connection con = DriverManager.getConnection(myConnectionURL);
               PreparedStatement ps = con.prepareStatement(sql)) {
              ps.setInt(1, userId);
              try (ResultSet rs = ps.executeQuery()) {
                  while(rs.next()) {
                      users.add(new User(rs.getInt("id"), rs.getString("name")));
                  }
              }
          } catch (SQLException e) {
              e.printStackTrace();
          }
          return users;
      
      class WhatIsJdbc{
        public static void main(String[] args) {
          String url = "jdbc:sqlite:path-to-db/chinook/chinook.db";
          try (Connection conn = DriverManager.getConnection(url){
      
            System.out.println("Got it!");
      
          } catch (SQLException e) {
            throw new Error("Problem", e);
          } 
        }
      }
      

      Compile and execute this code. Assuming all goes well, you will get an affirming message.

      Now, we’re ready for some SQL commands.

      Step 5. Query the database

      With the live connection object in hand, we can do something useful, like querying the database. Listing 5 shows how to query SQLite using the JDBC Connection and Statement objects.

      Listing 5. Querying the database with JDBC

      
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      import java.sql.ResultSet;
      import java.sql.Statement;
      
      
      class WhatIsJdbc{
        public static void main(String[] args) {
          String sql = "SELECT id, username FROM users WHERE id = ?";
          String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db";
          try (Connection conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement()) {
      
            try {
              ResultSet rs = stmt.executeQuery("select * from albums";);
              while (rs.next()) {
                String name = rs.getString("title");
                System.out.println(name);
              }
            } catch (SQLException e ) {
                  throw new Error("Problem", e);
            } 
      
          } catch (SQLException e) {
            throw new Error("Problem", e);
          } 
        }
      }
      
      

      In Listing 5 we use our Connection object to obtain a Statement object: conn.createStatement(). We then use this object to execute an SQL query: stmt.executeQuery(query).

      The executeQuery command returns a ResultSet object, which we then use to iterate over the data with while (rs.next()). In this example, you should see the album titles we’ve queried on as output.

      Notice that we also closed the connection, via a call to conn.close().

      PreparedStatements, batch updates, and transactions

      So far, we’ve covered the basics of using JDBC to connect to a database and issue SQL commands. While Statements and ResultSets work well for common scenarios, you’ll likely need additional options for larger or more complex applications. Fortunately, the JDBC library continues evolving to meet most database access needs.



      Source link

      admin

      admin

      • Trending
      • Comments
      • Latest
      Plant warning as bamboo causes £100,000 of damage to Hampshire property

      Plant warning as bamboo causes £100,000 of damage to Hampshire property

      January 31, 2022
      Social workers warned weeks before baby Mitchell died in 2019 | TV & Radio | Showbiz & TV

      Social workers warned weeks before baby Mitchell died in 2019 | TV & Radio | Showbiz & TV

      January 2, 2022
      Yorkshire nan on how to make Yorkshire puddings with no ingredients weighed

      Yorkshire nan on how to make Yorkshire puddings with no ingredients weighed

      February 15, 2022
      Newcastle transfer news: Last-gasp offer made for Dele Alli in late Everton hijack attempt | Football | Sport

      Newcastle transfer news: Last-gasp offer made for Dele Alli in late Everton hijack attempt | Football | Sport

      January 31, 2022
      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      0
      Boris Johnson slammed by Indie band for using their song ‘Blue Bunch Of Corrupt W****rs’ | Music | Entertainment

      Boris Johnson slammed by Indie band for using their song ‘Blue Bunch Of Corrupt W****rs’ | Music | Entertainment

      0
      Call Your Mom, Because Sue Grafton’s Alphabet Murder Mystery Books Are Becoming A Show

      Call Your Mom, Because Sue Grafton’s Alphabet Murder Mystery Books Are Becoming A Show

      0
      Release Date, Cast, And More

      Release Date, Cast, And More

      0
      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      May 17, 2022
      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      May 17, 2022
      Leading pollster warns cultures wars WILL destroy Britain | Politics | News

      Leading pollster warns cultures wars WILL destroy Britain | Politics | News

      May 17, 2022
      5 Summer Pieces I’m Buying on a Budget

      5 Summer Pieces I’m Buying on a Budget

      May 17, 2022

      Recent News

      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      May 17, 2022
      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      May 17, 2022
      Leading pollster warns cultures wars WILL destroy Britain | Politics | News

      Leading pollster warns cultures wars WILL destroy Britain | Politics | News

      May 17, 2022
      5 Summer Pieces I’m Buying on a Budget

      5 Summer Pieces I’m Buying on a Budget

      May 17, 2022
      Breaking News, US News, World News and Bollywood News

      Follow Us

      Browse by Category

      • Bollywood
      • Business
      • Entertainment
      • Fashion
      • Food
      • Health
      • Hollywood
      • Lifestyle
      • Music
      • Nature
      • Science
      • Sports
      • Technology
      • Travel
      • World News

      Recent News

      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      Gentleman Jack Gives Into Temptation In ‘I’m Not The Other Woman, She Is’

      May 17, 2022
      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      The real-life Tomb Raider game that’s not on consoles – Tomb Raider Experience hits London | Gaming | Entertainment

      May 17, 2022
      • Home
      • Privacy Policy

      © 2021 Updates News

      No Result
      View All Result

      © 2021 Updates News