MySQL connection error in Java - com.mysql.jdbc.Driver

I am trying to connect my Java application to a MySQL database and used the following lines of code:

import java.sql.*; 
public class AcceptValues extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

             String url = "jdbc:mysql://localhost:3306/db_name";
             String driver = "com.mysql.jdbc.Driver";
             String userName = "root";
             String password = "";
             try {
             Class.forName(driver);
             Connection conn = DriverManager.getConnection(url,userName,password);
             out.print("Connection estd");
             Statement st = conn.createStatement();
             st.executeQuery("insert into table_name values(2, 'testing');");
             }
             conn.close();
             } catch (Exception e) {
                 out.print("Error : " +e.getMessage());
             }
        }
}

I also set the class name to mysql-connector-java-5.1.29-bin.jar, which I downloaded from mysql site. But I still cannot connect to the database using the above lines of code and throws exeption com.mysql.jdbc.Driver as an error.

I am new to java development and any help would be greatly appreciated. Thank.

+4
source share
3 answers

mysql-connector-java-5.1.29-bin.jar WEB-INF/lib. , . .

+7

,

→ Java → → Jar ( )

,

,

import java.sql.*;
public class DBConn {

private String url = "jdbc:mysql://localhost:3306/test";
private String driver = "com.mysql.jdbc.Driver";
private String userName = "root";
private String password = "root";
private Connection con = null;

private void getConnection() {

     try {
         Class.forName(driver);
         if(con == null){
             con = DriverManager.getConnection(url,userName,password);
         }
         System.out.print("Connection estd");
     }catch (Exception e) {
         System.out.print("Error : " +e.getMessage());
    }
}


/**for desktop application */
public static void main(String[] arg){

    DBConn con = new DBConn();
    con.getConnection();
  }
}

,

import java.sql.*; 
public class AcceptValues extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

   DBConn con = new DBConn();
   con.getConnection();
}
}

, , ,

/

+3

exeption com.mysql.jdbc.Driver .

I met this problem, in most cases there are two reasons for this problem. one of them is the absence of the mysql jar file, two lose sight of starting the mysql service.

-1
source

All Articles