{"id":2071842,"date":"2022-01-03T20:39:00","date_gmt":"2022-01-03T18:39:00","guid":{"rendered":"http:\/\/nhub.news\/?p=2071842"},"modified":"2022-01-04T00:03:42","modified_gmt":"2022-01-03T22:03:42","slug":"jdbc-tutorial-part-1-connecting-to-a-database","status":"publish","type":"post","link":"http:\/\/nhub.news\/ru\/2022\/01\/jdbc-tutorial-part-1-connecting-to-a-database\/","title":{"rendered":"JDBC Tutorial Part 1: Connecting to a Database"},"content":{"rendered":"<p style=\"text-align: justify;\"><b>In this series, learn the basics of Java Database Connectivity. In Part 1, learn what a JDBC driver is and how to open and safely close database connections.<\/b><br \/>\nJoin the DZone community and get the full member experience. In this series of articles (and videos), you\u2019ll learn the basics of Java Database Connectivity, most frequently abbreviated as JDBC. All of the most popular persistence frameworks use JDBC behind the scenes, so having a solid understanding of the key concepts in JDBC is key when using JPA, Hibernate, MyBatis, jOOQ, or any other database framework for Java. The most important concepts that you need to know are: JDBC driver Connection pool In addition to these concepts, you need to understand how to make calls to the database: specifically, how to run an SQL query from a Java program, how to process the results, and how to insert, update, and delete data. This article focuses on what a JDBC driver is and how to open and safely close database connections. The next articles talk about executing SQL statements and using connection pools. The source code is available on GitHub with each part in independent Maven projects. Here\u2019s a video version of this article, in case you want to see the concepts in action: Before we start, we need a database to play with. I assume you have installed MariaDB on your computer or have a SkySQL account with a database instance running in the Cloud (you can create an account for free). In my case, I have it running on my computer, so I can connect to the server using the mariadb client tool using the database user that I created beforehand: You might have to specify the host, port, and database username for your own instance. For example, in the case of SkySQL, you can use something like the following: Let\u2019s create a new database with the name jdbc_demo and a table with the name programming_language as follows: Use the quit command to exit the client tool. JDBC is an API specification: a set of interfaces that define what the technology can do. It doesn\u2019t implement the details of how to connect to a specific database. Instead, it lets database vendors implement the logic required to \u201ctalk\u201d to their databases. Each database has a different way to \u201cspeak\u201d through the network (the database client\/server protocol), so each database needs custom Java code compatible with JDBC. This code is packaged as a JAR file called JDBC driver. For example, in the case of MariaDB (a multi-purpose database), the JDBC driver is MariaDB Connector\/J. You have to download the JAR file that contains the driver and add it to your Java project. If you are using Maven, you can add the dependency to the pom.xml file. When you search for the JDBC driver of the database you want, use the latest version of the driver if possible. This way you\u2019ll get the latest security patches, performance improvements, and features. Let\u2019s create a new Java application with a simple pom.xml file that includes the MariaDB JDBC driver: As you can see, the JDBC driver is called mariadb-java-client. We have also added the Maven Shade Plugin to be able to generate an executable JAR that includes the JDBC driver (Uber JAR). You can place this pom.xml file in an empty directory and run mvn package to download the MariaDB Connector\/J dependency and check that the project builds correctly: We are going to code a simple Java application that opens a connection and closes it: no data manipulation for now. That\u2019s covered in the next article of this series. The application includes a Java entry point ( main) and a couple of methods. You can use any IDE to create the class or we can manually add a new subdirectory for the Java package where our code will reside. On Linux-like systems, this will look like the following: If you are wondering what that little creature is, it\u2019s a seal. MariaDB\u2019s logo is a sea lion. Since I wasn\u2019t able to find a sea lion emoji, I went for a seal instead. Close enough I guess. Back to the tutorial&#8230; Here\u2019s the structure of the Java app (add this into a new Application.java file in the directory we created): With JDBC, Java applications establish database connections through the DataSource interface or the DriverManager class. For simplicity, we are going to use the latter in this step of the tutorial, but most serious applications should use a connection pool (we\u2019ll learn this in the third article of this series). To connect to a database using JDBC, we need something called a connection URL (or JDBC connection string). Depending on your specific database the connection URL will look different, but in general, a connection string looks like this: The part identifies the kind of database. The part is database-specific and typically contains information on the location of the database instance and configuration parameters. For example, in the case of a MariaDB server running locally, the connection URL looks something like this: Or, if you are using SkySQL: You can find examples of connection URLs for all databases online and in the official documentation of the JDBC drivers. Here\u2019s how we can connect to the database from the Java application: First, we added a Java field of type Connection to the class. This interface contains all the methods to interact with the database. Second, we used the DriverManager class to get a new connection to the database using the connection URL and the database username and password. Third, we showed a message confirming that the connection is valid. Notice that we added a throws clause to the method signatures. Most JDBC operations throw an SQLException in case of errors. We can handle it in a catch block or in the case we want to show an error message to the user. In this demo, we won\u2019t deal with exception handling. Before the application finishes, we need to close the database connection. A connection consumes resources that should be released: both operating-system-level resources and database resources such as cursors or handles. Here\u2019s how we can close the database connection: That\u2019s it really. But, wait! There\u2019s a catch here. Since later in this series, we will be adding functionality between the openDatabaseConnection() and closeDatabaseConnection() methods, things could go wrong at any point and we might not be able to close the database connection properly. Hopefully, this can be easily solved by enclosing the code in a try block and closing the connection in a finally block. The finally block always gets executed even if a problem occurs and an exception is thrown. Here\u2019s the final result with the problem fixed: Run mvn clean package to build the final JAR and run it from the command line as follows: Here\u2019s a screenshot of the output: Try manually throwing an exception somewhere before closing the connection to simulate an error and see how the connection is closed regardless: In the next article, we\u2019ll learn how to use the connection object to send SQL statements to the database. Opinions expressed by DZone contributors are their own.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this series, learn the basics of Java Database Connectivity. In Part 1, learn what a JDBC driver is and how to open and safely close database connections. Join the DZone community and get the full member experience. In this series of articles (and videos), you\u2019ll learn the basics of Java Database Connectivity, most frequently [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2071841,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[93],"tags":[],"_links":{"self":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/posts\/2071842"}],"collection":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/comments?post=2071842"}],"version-history":[{"count":0,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/posts\/2071842\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/media\/2071841"}],"wp:attachment":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/media?parent=2071842"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/categories?post=2071842"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/tags?post=2071842"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}