📜  java connect mariadb - Java (1)

📅  最后修改于: 2023-12-03 15:01:29.174000             🧑  作者: Mango

Java Connect MariaDB

MariaDB is a popular open source relational database management system. In this tutorial, we will learn how to connect to MariaDB database using Java.

Prerequisites

Before proceeding, make sure you have the following tools installed on your system:

  • Java Development Kit (JDK) version 8 or higher
  • MariaDB database server
  • MariaDB JDBC driver
Step 1: Create a new Java project

The first step is to create a new Java project in your favorite Integrated Development Environment (IDE). In this tutorial, we will use Eclipse IDE.

Follow the below steps to create a new Java project:

  1. Open Eclipse IDE and click on File -> New -> Java Project.
  2. Enter a project name and click Finish.
Step 2: Add MariaDB JDBC driver to the project

The next step is to add the MariaDB JDBC driver to the Java project. Follow the below steps to add the JDBC driver:

  1. Download the latest version of the MariaDB JDBC driver from the official website.
  2. Extract the downloaded ZIP file.
  3. In Eclipse IDE, right-click on the project and select Build Path -> Configure Build Path.
  4. Click on the Libraries tab.
  5. Click on the Add External JARs button and select the extracted JDBC driver JAR file.
Step 3: Connect to MariaDB database

Now that we have added the JDBC driver to the project, we can use it to connect to the MariaDB database.

Use the below code snippet to establish a connection to the MariaDB database:

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

public class MariaDbConnection {
   public static void main(String[] args) {
      Connection conn = null;
      try {
         conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/db_name", "user", "password");
         System.out.println("Connection successful!");
      } catch (SQLException e) {
         System.out.println("Connection failed!");
         e.printStackTrace();
      } finally {
         try {
            conn.close();
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }
   }
}

Make sure to replace db_name, user, and password with your own database details.

Conclusion

In this tutorial, we learned how to connect to MariaDB database using Java. We covered the steps to create a new Java project, add MariaDB JDBC driver to the project, and connect to the database.