如何修复:“没有为jdbc找到合适的驱动程序:mysql:// localhost / dbname”错误

时间:2022-11-07 19:16:51

i am trying to create connection to my musql in java. when i do it with Main it works with no problem, but when i use apache its return the error:

我试图在java中创建与我的musql的连接。当我用Main做它没有问题,但当我使用apache时它返回错误:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/database_name..

i read the look alike questions and none of them helps me.

我读了相似的问题,但没有一个能帮助我。

i use JDK 8 and JDBC 5. the JDBC driver locate in the project lib and i included it in the build path and this is my code:

我使用JDK 8和JDBC 5. JDBC驱动程序位于项目lib中,我将其包含在构建路径中,这是我的代码:

 // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost:3306/program1";

   //  Database credentials
   static final String USER = "user";
   static final String PASS = "pass";

   private static Connection conn = null;


   /*
    * Create connection to the DB in singletone
    * */
   protected static Connection getConnection() throws ClassNotFoundException, SQLException
   {
           if(conn==null)
           {
               try 
               {
                   // Register JDBC driver
                  //Class.forName(JDBC_DRIVER);

                   // Open connection
                   conn = DriverManager.getConnection(DB_URL,USER,PASS);
               } 
               catch ( SQLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   if(conn != null)
                        conn.close();
               }
           }

       return conn;
   }

in the moment the debug run the line " conn = DriverManager.getConnection(DB_URL,USER,PASS);" i get the exception.

在调试运行行“conn = DriverManager.getConnection(DB_URL,USER,PASS);”时我得到了例外。

What is causing this error? and why when i run it from main it works?

导致此错误的原因是什么?为什么当我从main运行它有效?

1 个解决方案

#1


1  

You need to download mysqlConnector, and add is as an lib to your project.

您需要下载mysqlConnector,并将add作为lib添加到您的项目中。

https://dev.mysql.com/downloads/connector/j/

#1


1  

You need to download mysqlConnector, and add is as an lib to your project.

您需要下载mysqlConnector,并将add作为lib添加到您的项目中。

https://dev.mysql.com/downloads/connector/j/