测试Mybatis中的数据库连接

 有时候,在使用jdbc连接数据库时发生bug,不知道是哪一步骤发生错误,可以简单的使用自己配置的方法来测试是否能成功连接,其实连接不上数据库时,主要问题还是在url这个问题上:

1、url需要配置时区,例如:serverTimezone=GMT%2B8

2、使用SSL加密协议,默认使用:useSSL=false

3、mysql版本和mybatis版本更新后,驱动改为:

driver-class-name: com.mysql.cj.jdbc.Driver

4、使用中文更新数据库为”?"时,需要调整mysql的编码格式,同时url中也需要明确编码:characterEncoding=utf-8


import org.junit.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 java.sql.DriverManager;
import java.sql.SQLException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallProductApplicationTests {
    @Test
    public void testRemoteJdbc() {
        String url = "jdbc:mysql://192.168.56.10:3306/database_table_name?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf-8;
        String username = "root";
        String password = "root";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            DriverManager.getConnection(url, username, password);
            System.out.println("连接远程数据库成功");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("连接远程数据库失败");
            e.printStackTrace();
        }
    }

}