Home >Database >Mysql Tutorial >How Spring connects to Mysql database
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>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; } }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.
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!