search
HomeDatabaseMysql TutorialHow to connect to MySQL database in Java

How to connect to MySQL database in Java

May 30, 2023 pm 03:10 PM
mysqljava

First of all, since it is a version 8 database, the writing method of the configuration class is different from that of version 5. Please note that when using idea or eclipse at the same time, you need to import the jar package

If you want to download For jar packages with 8 different versions, you only need to modify 8.0.28 to the specified version.

The method of idea to import jar package is as follows:

How to connect to MySQL database in Java

How to connect to MySQL database in Java

How to connect to MySQL database in Java

How to connect to MySQL database in Java

How to connect to MySQL database in Java

##Then comes the code part. First create the table:

CREATE TABLE `train_message` (
                                 `id` int NOT NULL AUTO_INCREMENT COMMENT '主键id',
                                 `train_name` varchar(20) NOT NULL COMMENT '列车名',
                                 `origin` varchar(30) NOT NULL COMMENT '始发地',
                                 `terminal` varchar(30) NOT NULL COMMENT '终到地',
                                 `departure_time` timestamp NOT NULL COMMENT '出站时间',
                                 `state` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '正常' COMMENT '列车状态',
                                 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb3

Then create the connected configuration class DbConfig.java, localhost is the ip address of the machine, If there is a server, fill in the IP address of the server. message is the name of the database. Here is a picture showing the name that many novices misunderstand

How to connect to MySQL database in Java

##

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

/**
 *  数据库配置类
 *  @author 景苒
 */
public class DbConfig {
    public Connection dbConfig() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (Exception e) {
            System.out.print("加载驱动失败!");
            e.printStackTrace();
        }
        String url = "jdbc:mysql://localhost:3306/message?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true";
        String user = "root";
        String password = "123456";
        return DriverManager.getConnection(url, user, password);
    }
}
How to connect to MySQL database in JavaThen write the main function Main.java. The function body of the main function here can be written at the end. Just open the comment if you need any function. For a quick comment method, select this sentence and press ctrl plus /. All annotated.

import java.sql.SQLException;

/**
 * 主函数,调用功能
 * @author 景苒
 */
public class Main {
    public static void main(String[] args) throws SQLException {
//        new GetMessage().getMessage();
//        new UpdateTrainState().updateTrainState();
//        new InsertTrain().insertTrain();
//        new GetNumber().getNumber();
    }
}

Then there are the functions of each:

1. Query all train information from Shenyang to Wuhan, sorted by departure time

Build the GetMessage.java class

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 查询沈阳到武汉的所有列车信息,按出发时间先后排序
 * @author 景苒
 */
public class GetMessage {
    public void getMessage() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        String sql = "select * from `train_message` where origin = ? and terminal = ? ORDER BY departure_time ASC";
        String origin = "沈阳";
        String terminal = "武汉";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, origin);
        ps.setString(2, terminal);
        ResultSet rs = ps.executeQuery();
        try {
            while (rs.next()) {
                System.out.println("列车名:" + rs.getString("train_name")
                        + " 始发站:" + rs.getString("origin")
                        + " 终到站:" + rs.getString("terminal")
                        + " 出发时间:" + rs.getString("departure_time")
                        + " 列车状态:" + rs.getString("state"));
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ps.close();
            con.close();
        }
    }
}

2. Modify the status of T2255 train to out of service

Create the UpdateTrainState.java class

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 修改T2255列车的状态为停运
 * @author 景苒
 */
public class UpdateTrainState {
    public void updateTrainState() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        String sql = "UPDATE `train_message` SET state = '停运' WHERE train_name = 'T2255'";
        Statement statement = con.createStatement();
        try {
            int i = statement.executeUpdate(sql);
            if (i > 0) {
                System.out.println("更新成功");
            }else {
                System.out.println("更新失败");
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            statement.close();
            con.close();
        }
    }
}

3. Add a new train information (enter it yourself)

Build the InsertTrain.java class

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 新增一辆列车信息(自己输入)
 * 始发时间为timestamp类型,输入时需要确保格式正确,如:2019-01-01 00:00:00
 * @author 景苒
 */
public class InsertTrain {
    public void insertTrain() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        Scanner scanner = new Scanner(System.in);
        String sql = "insert into `train_message` values(null, ?, ?, ?, ?, default)";
        System.out.print("请输入列车名:");
        String trainName = scanner.nextLine();
        System.out.print("请输入始发站:");
        String origin = scanner.nextLine();
        System.out.print("请输入终到站:");
        String terminal = scanner.nextLine();
        System.out.print("请输入始发时间:");
        String departureTime = scanner.nextLine();
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, trainName);
        ps.setString(2, origin);
        ps.setString(3, terminal);
        ps.setString(4, departureTime);
        try {
            int i = ps.executeUpdate();
            if (i > 0) {
                System.out.println("添加成功");
            }else {
                System.out.println("添加失败");
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ps.close();
            con.close();
        }
    }
}

4. Query the number of trains with normal status

Build the GetNumber.java class

import java.sql.Statement;

/**
 * 查询状态为正常的列车数量
 * @author 景苒
 */
public class GetNumber {
    public void getNumber() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        String sql = "select count(state) from `train_message` where state = '正常'";
        Statement statement = con.createStatement();
        try {
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.println("状态为正常的列车数量为:" + resultSet.getInt(1));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            statement.close();
            con.close();
        }
    }
}

Finally, attach the attribute structure diagram and sample of navicat Inserted statements

How to connect to MySQL database in Java

How to connect to MySQL database in Java Just write a few data according to your own needs. The above is the example code for java to connect to mysql database, and eclipse also Much the same, except for the way of importing the jar package.

The above is the detailed content of How to connect to MySQL database in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.