Spring boot 2.6.2 MSSQL2019 연동 테스트

2022. 1. 18. 18:50IT개발/Spring Boot & Spring Data Rest & JPA

반응형

자~ 최신 spring boot를 이용하여 MSSQL 2019 버전에 한번 접속해보자!

application.properties

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.jdbc-url=jdbc:sqlserver://mylocal-pc:1433;databaseName=test;
spring.datasource.username=test
spring.datasource.password=test
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2019Dialect

 

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
</dependency>

 

DBTest.java


import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import lombok.extern.slf4j.Slf4j;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class DbInfoTest {
    @Autowired
    DataSource dataSource;

    @Test
    public void connection() throws SQLException {
        Connection connection = null;
        Statement stmt = null;
        ResultSet resultSet = null;
        try {
            connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            log.info("URL : " + metaData.getURL());
            log.info("DriverName : " + metaData.getDriverName());
            log.info("UserNmae : " + metaData.getUserName());
            stmt = connection.createStatement();
            resultSet = stmt.executeQuery("SELECT TOP 1000 * FROM SOMETHING");
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            final int columnCount = resultSetMetaData.getColumnCount();
            while (resultSet.next()) {
                Object[] values = new Object[columnCount];
                for (int i = 1; i <= columnCount; i++) {
                    values[i - 1] = resultSet.getObject(i);
                    System.err.print(String.format("%-20.10s | ", values[i - 1]));
                }
                System.err.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            resultSet.close();
            stmt.close();
            connection.close();
        }
    }
}

 

실행결과

반응형