Connect from Java to MySQL using Eclipse

I will explain how to operate MySQL in Java. This time I will install XAMPP in a Windows environment and use MySQL.

Advance preparation

-Installation of JDK ・ Installation of Eclipse ・ Installation of XAMPP -Preparation of JDBC driver

Eclipse preparation

1. Create a Java project

Create a new project to be used this time with ** "File (F)"> "New (N)"> "Java Project" ** on the upper left. image.png Make the project name easy to understand ** "MysqlTest" **. ** Click "Finish" ** to create.

image.png

2. Incorporate the JDBC driver into your project

Once the project is created, right-click on the project and select ** "Build Path (B)"> "Add External Archive (V) ..." ** to select the JDBC driver (mysql-connector-java-8.0). Open .19.jar). image.png image.png It is okay if ** mysql-connector-java-8.0.19.jar ** is added to the "reference library" directly under the project.

MySQL preparation

Start XAMPP and let MySQL ** "Start" **. image.png When you can start, click ** "Shell" ** on the right to start it. After starting, enter the following command to connect to MySQL as the root user. Please refer to this article for password settings.

python


mysql -u root -p

After connecting, create a database with the following command. This time we will create a database named ** "test_db" **.

python


CREATE DATABASE test_db;

If you can create it successfully, connect to the database you just created with the following command.

python


USE test_db;

The flow up to this point is as shown in the image below. image.png

Next, create a table and store the data. This time we will create a table called ** "test" **. Enter the following command. * Don't forget the comma! If you make a typo, interrupt it with ** "\ c" ** and re-enter it.

python


CREATE TABLE test(
    id VARCHAR(3),
    name VARCHAR(10)
);

Once the table is created, we will store the data. Let's store 3 lines of data this time.

python


INSERT INTO test VALUES('001', 'Mandarin orange');
INSERT INTO test VALUES('002', 'Apple');
INSERT INTO test VALUES('003', 'Grape');

The flow up to this point is as shown in the image below. image.png

Let's check if the data is stored properly with the following command.

python


SELECT * FROM test;

image.png MySQL is now ready.

Connect to MySQL from Java

Now you're ready to go. From here, let's create a Java program, access the database created earlier, and display the data in the table.

First, right-click ** "src" ** in the ** "MysqlTest" ** project that you created first, and select "New (W)"> "Package" to select the package "java_mysql" **. Create a. image.png

Next, right-click the package you just created and select ** "New (W)"> "File" ** to create a file called ** "Test.java" **.

image.png If you can do so far, I will write the contents of ** "Test.java" **. I wrote the meaning of the code in the comments.

Test.java


package java_mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test {

	public static void main(String[] args) {
    
    //Variable preparation
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

    //SQL statement creation
		String sql = "SELECT * FROM test";

		try {
			//JDBC driver loading
			Class.forName("com.mysql.cj.jdbc.Driver");
			//Database connection
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db?serverTimezone=JST", "root", "root");
			//SQL execution preparation
			stmt = con.prepareStatement(sql);
			//Get execution result
			rs = stmt.executeQuery();

      //Until there is no data(rs.next()Until becomes false)repeat
			while (rs.next()) {
				String id = rs.getString("id");
				String name = rs.getString("name");

				System.out.println(id + ":" + name);
			}
		} catch (ClassNotFoundException e) {
			System.out.println("An error occurred while loading the JDBC driver");
		} catch (SQLException e) {
			System.out.println("There was an error accessing the database.");
		} finally {
			try {
				if (con != null) {
					con.close();
				}
			} catch (SQLException e) {
				System.out.println("There was an error accessing the database.");
			}
		}
	}

}

After writing the code, save it, right-click ** "Test.java" ** and execute it from ** "Run"> "Java Application" **.

image.png If the following is displayed on the console, it is successful.

image.png

Recommended Posts

Connect from Java to MySQL using Eclipse
[Java] Connect to MySQL
Connect to Aurora (MySQL) from a Java application
Connect from Java to PostgreSQL
Connect to MySQL 8 with Java
From installing Eclipse to executing Java (PHP)
Changes from Java 8 to Java 11
Sum from Java_1 to 100
From Java to Ruby !!
Ssh connect using SSHJ from a Java 6 app
Migration from Cobol to JAVA
How to jump from Eclipse Java to a SQL file
New features from Java7 to Java8
To connect from Spring to MySQL on virtual server (unsolved)
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
Connect to DB with Java
Using Docker from Java Gradle
Connect to oracle with eclipse!
[Android] Connect to MySQL (unfinished)
From Ineffective Java to Effective Java
I want to connect to Heroku MySQL from a client
Operation to connect multiple Streams @Java
Create a Java project using Eclipse
Upgrade from MYSQL5.7 to 8.0 on CentOS 6.7
Java to be involved from today
From Java to VB.NET-Writing Contrast Memo-
Java, interface to start from beginner
Change DB from SQLite to MySQL
[Java] Try to implement using generics
Switch from Eclipse to VS Code
The road from JavaScript to Java
java Eclipse How to debug javaScript
[Java] Conversion from array to List
Update MySQL from 5.7 to 8.0 with Docker
Sample code using Minio from Java
I can't log in to MySQL from Django when using docker-compose
I just want to write Java using Eclipse on my Mac
If you want to change the Java development environment from Eclipse
Try passing values from Java Servlet to iPhone app using JSON
I tried to display the calendar on the Eclipse console using Java.
Code Java from Emacs with Eclim
Switch from Eclipse to VS Code
Sample code using Minio from Java
Data processing using stream API from Java 8
[Java] How to calculate age using LocalDate
Convert from java UTC time to JST time
Using JavaScript from Java in Rhino 2021 version
Post to Slack from Play Framework 2.8 (Java)
Java: How to send values from Servlet to Servlet
[Java] Flow from source code to execution
Call Java methods from Nim using jnim
Introduction to monitoring from Java Touching Prometheus
Precautions when migrating from VB6.0 to JAVA
Memo for migration from java to kotlin
Type conversion from java BigDecimal type to String type
Access Forec.com from Java using Axis2 Enterprise WSDL
[Java] From two Lists to one array list
Upsert from Java SDK to Azure Cosmos DB
Run R from Java I want to run rJava
POST images from Android to PHP using Retrofit
Solution that gives an error when trying to connect to DB (MySQL) in Java
Migration from Eclipse to IntelliJ (on the way)
[Java] API creation using Jerjey (Jax-rs) in eclipse