The Wayback Machine - https://web.archive.org/web/20241002045931/https://www.geeksforgeeks.org/java-database-connectivity-with-mysql/
Open In App

Java Database Connectivity with MySQL

Last Updated : 17 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, we can connect our Java application with the MySQL database through the Java code. JDBC ( Java Database Connectivity) is one of the standard APIs for database connectivity, using it we can easily run our query, statement, and also fetch data from the database.

Prerequisite to understand Java Database Connectivity with MySQL

 1. You should have MySQL on your System.
2. You should have JDK on your System. 
3. To set up the connectivity, the user should have MySQL Connector to the Java (JAR file),
the 'JAR' file must be in classpath while compiling and running the code of JDBC.

Steps to download MySQL Connector

Step 1 – Search for MySQL community downloads.
Step 2 – Go to the Connector/J.
Step 3 – Select the Operating System platform-independent.
Step 4 – Download the zip file Platform Independent (Architecture Independent), ZIP Archive.

Step 5 – Extract the zip file.
Step 6 – Get the mysql-connector-java-8.0.20.jar file from the folder.

mysql-connector-java-8.0.20.jar_file_from_folder

Setting up Database Connectivity with MySQL using JDBC code

Users have to follow the following steps:

Step 1 – Users have to create a database in MySQL (for example let the name of the database be ‘mydb’ ).
Step 2 – Create a table in that database.

Example:

create table designation
(
code int primary key auto_increment,
title char(35) not null unique
);

This is MySQL code for creating a table.

Step 3 – Now, we want to access the data of this table using Java database connectivity.

  • Create a directory in your main drive (named gfg).
  • Now, inside gfg created two more directories one named as ‘src‘ and the other ‘lib‘.

directory_creation_in_cmd

  • Put the MySQL connector java jar file in the lib folder.

MySQL connector java jar file inside_lib_folder

Step 4 – We will write connectivity code in the src folder, To write connectivity code user must know the following information:

  • Driver class:- The driver class for connectivity of MySQL database “com.mysql.cj.jdbc.Driver”, after the driver has been registered, we can obtain a Connection instance that is connected to a particular database by calling DriverManager.getConnection():, in this method, we need to pass URL for connection and name and password of the database.
  • URL for Connection:- The connection URL for the mysql database is jdbc:mysql://localhost:3306/mydb (‘mydb’ is the name of database).
Specify to the DriverManager which JDBC drivers to try to make Connections use below line:
Class.forName("com.mysql.cj.jdbc.Driver");

To get connection object use below line :
Connection connection=DriverManager.getConnection("URL in string","username","password");

To get more clarification follow the connectivity code below:

Step 5 – In this src code, we will set up the connection and get all the data from the table. we have created the ‘check.java‘ file in the src folder.

Java




//Java program to set up connection and get all data from table
import java.sql.*;
 
public class GFG {
    public static void main(String arg[])
    {
        Connection connection = null;
        try {
            // below two lines are used for connectivity.
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/mydb",
                "mydbuser", "mydbuser");
 
            // mydb is database
            // mydbuser is name of database
            // mydbuser is password of database
 
            Statement statement;
            statement = connection.createStatement();
            ResultSet resultSet;
            resultSet = statement.executeQuery(
                "select * from designation");
            int code;
            String title;
            while (resultSet.next()) {
                code = resultSet.getInt("code");
                title = resultSet.getString("title").trim();
                System.out.println("Code : " + code
                                   + " Title : " + title);
            }
            resultSet.close();
            statement.close();
            connection.close();
        }
        catch (Exception exception) {
            System.out.println(exception);
        }
    } // function ends
} // class ends


 Output of ‘check.java‘ file in the src folder:

check.java_file_inside_source_folder

 Note:

  • To run the above code first create a table in your MySQL database and add some data manually.
  • To compile the above code use “javac -classpath ..\lib\mysql-connector-java-8.0.20.jar;. Check.java“.
  • To run the above code use “java -classpath ..\lib\mysql-connector-java-8.0.20.jar;. Check“.


Previous Article
Next Article

Similar Reads

Introduction to JDBC (Java Database Connectivity)
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for Java applications to communicate with various databases. It provides the language with Java database connectivity standards. It is us
6 min read
How to Generate Database Dump of MySQL Database in Linux?
We will learn how to Backup and Restore your MySQL Database with Mysqldump query in LINUX. We had always a need that if the production database is corrupted somehow, we should be able to recover it, for recovering we should always keep a backup of the database at particular instances. So, data rollback can be done. First, we will create a Database
2 min read
Checking Internet Connectivity using Java
Checking Internet connectivity using Java can be done using 2 methods: 1) by using getRuntime() method of java Runtime class. 2) by using methods of java URL and URLConnection classes. #Java Runtime Class:This class is used to interact with java runtime environment (Java virtual machine) in which the application is running. It provides methods/func
2 min read
How to pre populate database in Android using SQLite Database
Introduction : Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Database. To prepopulate a SQLite database in an Android
7 min read
PHP | MySQL Database Introduction
What is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL is a database system that runs on a server.MySQL
4 min read
PHP | MySQL ( Creating Database )
What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty, and admin staff etc. which helps in efficient retr
3 min read
MySQL | Database Files
Whenever MySQL database installation is done, all the database related data and metadata are stored in one folder. This is the actual database schema with some values in it. Let us explore more about it. The file extensions are as follows: .frm – This is the extension of file which contains the schema or definition of the table..myd – This is the e
5 min read
How to Import and Export Data to Database in MySQL Workbench?
Utilizing MySQL Workbench, a unified visual database designing or graphical user interface tool is necessary when working with database architects, developers, and administrators. It was made and is updated by Oracle. It offers comprehensive administration tools for server configuration, user administration, backup, and many other tasks as well as
3 min read
Deploying Spring Boot Application with MySQL Database on Azure
Azure is Microsoft’s cloud platform, just like Google has its Google Cloud and Amazon has its Amazon Web Service or AWS.000. Generally, it is a platform through which we can use Microsoft’s resources. Cloud Deployment is gaining huge traction nowadays as users love the concept of Cloud over on-premise infrastructure. This article gives a lucid expl
3 min read
Spring Boot - CRUD Operations using MySQL Database
CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a developmental point perspective in programming that also
7 min read
Microsoft Azure - Using Flexible Server in Azure Database for MySQL
Pre-requisite: Azure VM Azure Database for MySQL is a PaaS implementation of MySQL in the Azure cloud. It provides high availability at no extra charge, as well as scalability as needed, automatic backups, and point-in-time restores. Connection security is provided by the server, which enforces firewall restrictions and, optionally, requires SSL co
2 min read
Spring Batch Example - Read and Process CSV File to MySQL Database
GeekMart is a multinational technology company that focuses on the e-commerce business. It has a large number of suppliers who supply huge volumes of products to them. Suppliers share the product details in CSV file format. Help GeekMart to read the product details from the CSV file and store it in the “Product” table of MySQL database. Requirement
7 min read
How to integrate Mysql database with Django?
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Installation Let's first understand how to install MySQL to install the Mysql
2 min read
How to Show Schema of a Table in MySQL Database?
A table schema in MySQL database defines the structure of table, including columns, data types, relationships between columns, etc. It is a blueprint for the table, describing how data is organized in the table and how it relates to other tables in the database. To see the schema of a table in MySQL database, use the DESCRIBE command. How to Check
2 min read
Checking MySQL Database Size in Linux
MySQL is the most popular open-source database among developers. It was developed and managed by Oracle Corporation and initially released on 23 May 1995. It is compatible with each operating system, Like(Linux, Windows, and macOS) which is major support for web-based applications. In this article, we are going to see how to get the size of a datab
2 min read
How to Add an Admin User to WordPress Database via MySQL?
Adding an admin user to your WordPress database via MySQL can be necessary in situations where you cannot access the WordPress dashboard. This article will walk you through the process step-by-step. Why Add an Admin User via MySQL?Sometimes, you might lose access to your WordPress dashboard due to forgotten credentials, plugin conflicts, or other i
4 min read
Create a drop-down list that options fetched from a MySQL database in PHP
In many scenarios, we may need to create a dropdown input that can display all the options consistent with the current state of the database. This form of input is used many times in real life and the following examples may help to understand the same. A set of students who have unique registration numbers.A set of branch names and their branch ids
4 min read
PHP | Inserting into MySQL database
Inserting data into a MySQL database using PHP is a crucial operation for many web applications. This process allows developers to dynamically manage and store data, whether it be user inputs, content management, or other data-driven tasks. In this article, We will learn about How to Inserting into MySQL Database Using PHP in detail Inserting into
6 min read
Spring Boot 3.0 - JWT Authentication with Spring Security using MySQL Database
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security . In this article, we'll learn how to implement JWT authentication and authorization in a Spring Boot 3.0 application u
9 min read
MySQL | DATABASE() and CURRENT_USER() Functions
In MySQL, certain functions provide crucial information about the current session which can be particularly useful when working with multiple databases or managing user permissions. Two such important functions are DATABASE() and CURRENT_USER(). In this article, We will learn about the MySQL DATABASE() and CURRENT_USER() Functions with the help of
3 min read
Database Backup from MySQL
Backing up your MySQL database is crucial for data protection and recovery. There are several methods available to create backups each with its own benefits and use cases. In this article, we will explore four popular methods for backing up a MySQL database such as using mysqldump, phpMyAdmin, MySQL Workbench and file system snapshots. Database Bac
4 min read
MySQL vs CockroachDB: Which SQL Database is Better in 2024
It is important to choose the right relational database management system (RDBMS) for your application so that it scales, performs, and maintains data integrity. In today’s data-driven world, there are two key players: MySQL and CockroachDB. SQL-based, both of them offer powerful ways to interact with data from within the software. However, under t
9 min read
MySQL vs Firebird: Which Database System is Better in 2024
The choice of a database system is very significant in the ever-changing world of web development and serves as the bedrock for any digital project. In this era of technological advances, MySQL and Firebird are the two main contenders with different features and capabilities. The year 2024 needs a thorough examination of the attributes that make th
9 min read
MySQL vs H2: Which Database System is Better in 2024
The world of web development is a battlefield, and data reigns supreme. But where do you store your precious information? Choosing the right database system is like selecting a champion for your project – a reliable warrior that safeguards your data while ensuring smooth operation. In this article, two contenders emerge: MySQL and H2. Both are open
9 min read
MySQL | Common MySQL Queries
MySQL server is a open-source relational database management system which is a major support for web based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. Even all social networking websites mainly Facebook, Twitter, and Google depends on MySQL dat
9 min read
Functions in MySQL | Numeric, String and Date Time Functions in MySQL
In MySQL, functions play a crucial role in performing various operations on data, such as calculations, string manipulations, and date handling. These built-in functions simplify complex queries and data transformations, making it easier to manage and analyze data within a database. In this article, we will look at these different categories of MyS
4 min read
Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
In this article, we will be learning about how to do basic database operations using JDBC (Java Database Connectivity) API in Java programming language. These basic operations are INSERT, SELECT, UPDATE, and DELETE statements in SQL language. Although the target database system is Oracle Database, the same techniques can be applied to other databas
6 min read
JUnit Testing For MySQL Project in Java
For testing a software project, automated testing is always good and that will produce error-prone results. In the case of manual testing, there are possibilities of human errors. In this article let us take a sample project and let us see how to write JUnit test cases for it. Example Project Project Structure: As this is the Maven-driven project,
6 min read
Adding MySQL Connector to the Java Project in Apache NetBeans
Adding MySQL Connector Java to the Java Project sometimes creates a fuss for the programmer. In this article, we have provided the steps to install MySQL Connector JAR file using the Connector/J driver and add the MySQL Connector/J to your project. Note: Before downloading the MySQL connector, you should be clear about the version of the MySQL you
2 min read
Inserting Single and Multiple Records in MySQL using Java
Java Database Connectivity is an API that helps us to connect a Java program to any SQL Database Instance. This connection gives power to developers to programmatically insert, delete, or update data from the database. JDBC contains in-built methods to run queries and updates on the database. In this article, we will learn how to insert single and
6 min read
Article Tags :
Practice Tags :