Home >Database >Mysql Tutorial >How Spring connects to Mysql database

How Spring connects to Mysql database

WBOY
WBOYforward
2023-05-26 13:22:251720browse

1. Create a Maven project

How Spring connects to Mysql database

##2. Import the coordinates

 Add the following coordinates in

pom.xml, And click refresh in the upper right corner.

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.15</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.15</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
    </dependencies>

How Spring connects to Mysql database

3. Managed DataSource class

 Create a class named

AppConfig. Host the DataSource class and add the @Configuration annotation. Pay attention to setting the specified URL, username, and password to connect to the database.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;


@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource d = new DriverManagerDataSource() ;
        d.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC"); //设置url
        // 上述的test为你的数据库名
        d.setUsername("root"); //设置账号
        d.setPassword("root"); //设置密码
        return d;
    }

}

How Spring connects to Mysql database

4. Test

 Create a

Test class. Get the database connection through DataSource. and output.

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class Test {


    public static void main(String[] args) throws SQLException {
        ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
        DataSource d = (DataSource) ac.getBean("dataSource");
        Connection c = d.getConnection(); //获取连接
        System.out.println(c);
    }
}

The following code appears on the console, which means the connection is successful.

How Spring connects to Mysql database

The above is the detailed content of How Spring connects to Mysql database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete