Springboot connects to SQL Server database through JDBC

Springboot connects to SQL Server database through JDBC

Due to the needs of the project, I wrote a simple case of connecting to the SQL Server database (server v2019) through JDBC, which added the time required to calculate the database connection and execute a SQL language to fetch data. Welcome to refer if necessary.

1. The pom.xml file imports the driver

SQL Server-driven Maven warehouse coordinates
SQL Severe official website introduction

In the way of database driver mapping, add the following dependency in the pom.xml file

		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>mssql-jdbc</artifactId>
			<version>9.2.0.jre8</version>
		</dependency>

2. Connection code

The idea is to trigger the database connection operation through a Rest interface "/db", where the return value is the time to connect to the database and execute the SQL statement.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.*;

@RestController
public class TestCon {
    
    

    @GetMapping("/db")
    public String dbConnect() throws ClassNotFoundException {
    
    
        String url="jdbc:sqlserver://;serverName=localhost;databaseName=master";
        String user="sa";
        String pwd="SA@12345";
        String conTime = "";

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        try {
    
    
            // 1.获取开始时间
            long startTime = System.currentTimeMillis();

            // 2. 建立数据库连接
            Connection connection = DriverManager.getConnection(url, user, pwd);

            System.out.println("数据库连接成功");

            // 3.获取传输器
            Statement st = connection.createStatement();

            // 4.通过传输器发送SQL到服务器执行并且返回执行结果
            String sql = "SELECT Column1, Name FROM yiqi.dbo.NewTable;";

            ResultSet rs = st.executeQuery(sql);
            // 5.数据处理
            while (rs.next()) {
    
    
                int id = rs.getInt("Column1");
                String name = rs.getString("Name");
                System.out.println(id + ":" + name);
            }

            // 6. 获取结束时间,并计算连接数据库,执行SQL语句时间
            long endTime = System.currentTimeMillis(); //获取结束时间
            conTime = "程序运行时间:" + (endTime - startTime) + "ms";
            System.out.println(conTime); //输出程序运行时间

        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
        return conTime;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46660849/article/details/132073743