Jdbc application in java

Lesson: JDBC Basics

In this lesson you will learn the basics of the JDBC API.

  • Getting Started sets up a basic database development environment and shows you how to compile and run the JDBC tutorial samples.
  • Processing SQL Statements with JDBC outlines the steps required to process any SQL statement. The pages that follow describe these steps in more detail:
    • Establishing a Connection connects you to your database.
    • Connecting with DataSource Objects shows you how to connect to your database with DataSource objects, the preferred way of getting a connection to a data source.
    • Handling SQLExceptions shows you how to handle exceptions caused by database errors.
    • Setting Up Tables describes all the database tables used in the JDBC tutorial samples and how to create and populate tables with JDBC API and SQL scripts.
    • Retrieving and Modifying Values from Result Sets develop the process of configuring your database, sending queries, and retrieving data from your database.
    • Using Prepared Statements describes a more flexible way to create database queries.
    • Using Transactions shows you how to control when a database query is actually executed.
    • Using JdbcRowSet Objects
    • Using CachedRowSetObjets
    • Using JoinRowSet Objects
    • Using FilteredRowSet Objects
    • Using WebRowSet Objects
    • Using Large Objects
    • Using SQLXML Objects
    • Using Array Objects
    • Using DISTINCT Data Type
    • Using Structured Objects
    • Using Customized Type Mappings
    • Using Datalink Objects
    • Using RowId Objects

    Источник

    Lesson: JDBC Introduction

    The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a relational database.

    JDBC helps you to write Java applications that manage these three programming activities:

    1. Connect to a data source, like a database
    2. Send queries and update statements to the database
    3. Retrieve and process the results received from the database in answer to your query

    The following simple code fragment gives a simple example of these three steps:

    public void connectToAndQueryDatabase(String username, String password) < Connection con = DriverManager.getConnection( "jdbc:myDriver:myDatabase", username, password); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) < int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); >>

    This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It’s that simple.

    JDBC Product Components

    JDBC includes four components:

    1. The JDBC API — The JDBC™ API provides programmatic access to relational data from the Java™ programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment. The JDBC API is part of the Java platform, which includes the Java™ Standard Edition (Java™ SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.
    2. JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple. The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.
    3. JDBC Test Suite — The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.
    4. JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in a three-tier architecture.

    This Trail uses the first two of these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test relational database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs.

    Источник

    How to use JDBC to connect database in Java project

    When working with Java applications, reading and writing data to a relational database is a must-have skill that we need to know. So, in this article, we will learn how to connect our java application to database based on JDBC.

    Table of contents

    How to connect a JDBC driver to the database

    JDBC exemplifies the facade pattern in which the real workings of the specific implementation are hidden behind the standard JDBC API. The JDBC API is always backed by a vendor-specific code generally called by the driver.

    There are several JDBC classes and interfaces that are used by most JDBC applications. These includes the DriverManager , which maintains a registry of drivers, which are the vendor’s implementation of JDBC, the Connection object which represents the actual connection to a relational database.

    The Statement and PreparedStatement types which encapsulates the SQL command we want to execute, and the ResultSet which represents the data returned by our SQL command.

    There are different ways to connect depending on the circumstances. In this section, we will cover some connection methods:

    • DriverManager with Services
    • Class.forName() with DriverManager
    • DataSource
      • JNDI
      • Java / Jakarta EE
      • CDI

      Using DriverManager with Services

      When we create a JDBC connection, we do so by giving JDBC a set of properties which consist of a URI identifying the specific driver needed, as well as username, password, and other vendor-specific properties. This operation is performed by the DriverManager when calling the getConnection() method. Since we’re using the MySQL database, we will use the driver provided by MySQL, which is called Connector J . We can tell JDBC to use the Connector J driver by passing in a URI specific to that driver like the following code.

      import java.sql.Connection; import java.sql.DriverManager; . public class Component  public boolean tryConnection() throws Exception  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels?" + "user=root&password=12345&serverTimezone=UTC"); boolean isValid = connection.isValid(2); return isValid; > > 

      The driver documentation will tell us what this URI should be, but in most cases it follows the pattern of the JDBC schema, which is:

      If we want to use an Oracle database, the URI might look like:

      Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@myhost:1512:orcl", "root", "12345"); 

      If we use SQL Server, the URI might look like:

      Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost;" + "user=root;password=12345"); 

      To test if the connection is valid, we simply call isValid() on the connection object itself. If it connected to the database, it returns true, otherwise, it returns false. It’s important that we always close a database connection. If we do not close a database connection, our application may hold onto the database resources that it’s not using and that can be expensive in terms of memory, network socket connections, and threads.

      Each relational database vendor provides their own version of the JDBC driver, but all of them must conform with the interfaces and abstract classes defined by JDBC. At runtime, the JRE will load the vendor-specific driver, so that the JDBC API calls us make will be carried out by the underlying driver. The JRE will look at all of the registered JDBC drivers to determine which one matches the URI used to get the connection and we’ll instantiate that driver and pass it any other properties specified in the URI.

      The question we might be asking is how to we register the vendor’s driver.

      At runtime, the JRE will look into the jar files, META-INF services directory and look for a file name java.sql.Driver which lists the vendor-specific JDBC drivers that will be available at runtim.

      Using Class.forName() with DriverManager

      Prior to the JDBC 4, which was introduced with Java SE6, there was an extra step that was required when creating a JDBC connection. The vendor’s driver had to be explicitly loaded prior to being used. This was done using the Class.forName() method.

      public class Component  public boolean tryConnection() throws Exception  Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels?" + "user=root&password=12345&serverTimezone=UTC"); boolean isValid = connection.isValid(2); connection.close(); return isValid; > > 

      Until JDBC 4.0, we had to do this if we wanted to load a specific JDBC driver. When the Class.forName() method was executed, it would trigger the class loader to look for that driver and load it. In the process, a static code block in the Driver class was executed that registered the driver with the DriverManager. It was clunky, and when Java services were introduced in Java SE6, the Class.forName() was dropped in favor of listing the drivers and the java.sql.Driver file under the META-INF services directory.

      So, if Class.forName() is only used with JDBC drivers predating 4.0.

      Using DataSource

      If we’re doing development in Java EE, then we will probably be using the JDBC DataSource object instead of the DriverManager to get our connections. The DataSource type was introduced in JDBC 2.0 and first employed in the Java 2 Enterprise edition, the precursor to Java EE 6. The purpose of the DataSource object was to further abstract and encapsulate the process of obtaining a database connection.

        J2EE JNDI Instead of setting the JDBC driver URI and properties directly in the application code, they were declared in J2EE XML configuration files. At runtime, the J2EE container would read the JDBC XML configuration file and load the drivers it declared configuring them with the URI and properties defined in the configuration file. The developer would then access the DataSource from a context object provided by the J2EE component using JNDI, a directory services API.

       public class ProductsComponent_JNDI  public boolean getProductCount() throws Exception  InitialContext ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup("jdbc/mysql"); Connection connection = dataSource.getConnection("genius", "12345"); boolean isValid = connection.isValid(2); connection.close(); return isValid; > > 
       public class ProductsComponent_JEE implements SessionBean  @Resource(name="jdbc/mySql") DataSource dataSource; public boolean getProductCount() throws Exception  Connection connection = dataSource.getConnection(); boolean isValid = connection.isValid(2); connection.close(); return isValid; > > // Define @MySqlDataSource annotation @Qualifier @Target(FIELD, TYPE, METHOD>) @Retention(RUNTIME) public @interface MySqlDataSource  > public class DataSourceProducer  public MysqlDataSource mySqldataSource = null; @Produces @MySqlDataSource public DataSource produceDataSource()  // read properties from somewhere here if (mySqldataSource == null)  mySqldataSource = new MysqlDataSource(); mySqldataSource.setPassword("pluralsight"); mySqldataSource.setUser("root"); mySqldataSource.setURL("jdbc:mysql://localhost:3306/classicmodels?serverTimezone=UTC"); > return mySqldataSource; > > public static void main(String[] args) throws Exception  try  ProductsComponent_JEE component = new ProductsComponent_JEE(); DataSourceProducer producer = new DataSourceProducer(); component.dataSource = producer.produceDataSource(); if (component.getProductCount())  System.out.println("Demo m3c3: Try to Connect with JEE DataSource"); System.out.println("SUCCESS"); > else  System.out.println("Demo m3c3: Try to Connect with JEE DataSource"); System.out.println("FAILED"); > > catch (Exception exception)  util.ExceptionHandler.handleException(exception); > > 
       public class ProductsComponent_CDI @Inject @MySqlDataSource DataSource dataSource; public boolean getProductCount() throws Exception Connection connection = dataSource.getConnection(); boolean isValid = connection.isValid(2); connection.close(); return isValid; > > 

      Wrapping up

      Источник

      Читайте также:  Java google maps utils
Оцените статью