【问题标题】:facing problem while connecting java code to mysql将java代码连接到mysql时遇到问题
【发布时间】:2020-02-16 20:26:16
【问题描述】:

线程“主”com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException 中的异常:无法创建与数据库服务器的连接。尝试重新连接 3 次。放弃。

public class MyClass {

    public static void main(String[] args) throws Exception {



         String url= "jdbc:mysql://localhost:3306/first/?useUnicode=yes&autoReconnect=true&useSSL=false";
         String uname="root";
         String pass="****";

         Class.forName("com.mysql.jdbc.Driver");
         Connection con= DriverManager.getConnection(url,uname,pass);

         Statement st= con.createStatement();
         ResultSet rs=st.executeQuery("select name from sample_t where rollno=1");

         rs.next();
         String name1=rs.getString("name");
         System.out.println(name1);

         st.close();
         con.close();
    }

}

【问题讨论】:

  • 请发布完整的异常堆栈跟踪

标签: java mysql jdbc database-connection


【解决方案1】:

请检查您的 MySQL 服务器是否正在运行。

【讨论】:

    【解决方案2】:

    检查您的 MySQL 连接是否已启动并尝试更改 url,如下所示:

    String url= "jdbc:mysql://localhost/first/?useUnicode=yes&autoReconnect=true&useSSL=false";
    

    【讨论】:

      【解决方案3】:

      你可以试试这个方法

          try 
          {
              Class.forName("com.mysql.jdbc.Driver");     
              String url="jdbc:mysql://localhost:3306/first";
              String user="root";
              String pass="****";
              con=DriverManager.getConnection(url,user,pass);
      
              String query="select name from sample_t where rollno=?";
              pstmt=con.prepareStatement(query);
      
              System.out.println("Enter user id : ");
              pstmt.setInt(1, sc.nextInt());
              rs=pstmt.executeQuery();
      
              //Process the result
              if(rs.next())
              {
                  System.out.println("Roll No. : " +rs.getInt(1));
              }
      
              //closing connections
              sc.close();
              pstmt.close();
              rs.close();
              con.close();
      
          }   
      
          catch (Exception e) 
          {`
              e.printStackTrace();
          }
      

      【讨论】:

        猜你喜欢
        • 2019-11-27
        • 2011-07-13
        • 2017-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 2017-11-02
        • 1970-01-01
        相关资源
        最近更新 更多