欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to

程序员文章站 2022-05-01 16:25:36
...

项目简单的用jdbc访问数据库是报错:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to
代码如下:

public class JdbcMain {

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/local","root","******");
        connection.setAutoCommit(false);
        String sql = "insert into user_info values (?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,3);
        preparedStatement.setString(2,"用户3");
        preparedStatement.setInt(3,31);
        try {
            System.out.println("开始执行");
            preparedStatement.executeUpdate();
            connection.commit();
            System.out.println("事务提交结束");
        }catch (Exception e){
            connection.rollback();
            e.printStackTrace();
        }finally {
            if(preparedStatement!=null){
                preparedStatement.close();
            }
            if(connection!=null){
                connection.close();
            }
        }
    }
}

看了下使用的依赖是:

        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.29</version>
       </dependency>

尝试升级了版本,换成:

<!-- mysql驱动包 -->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.47</version>
       </dependency>

运行成功
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to
当然这个异常也有可能是其他问题造成的,这里只是我分享的其中一个问题的解决方案而已哈,不妨一试。