测试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();
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值