简体   繁体   中英

I am unable to connect mysql database in java(Intelli j)

I am trying to connect mysql database in java in Intellij idea

Please refer the source code below.

  package com.PS;
  import java.sql.*;

  public class Main  {

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

            String query = "select sname from student where rollno=16";
            String url = "jdbc:mysql://localhost:3306/abc?user=root";
            String uname = "root";
            String pass = "";

            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, uname, pass);
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(query);
            rs.next();
            String name = rs.getString("sname");
            System.out.println(name);
            conn.close();
            st.close();
        }
    }

But it gives error:

 Exception in thread "main" java.lang.ClassNotFoundException:
 com.mysql.cj.jdbc.Driver   at
 java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at
 java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    at java.base/java.lang.Class.forName0(Native Method)    at
 java.base/java.lang.Class.forName(Class.java:340)  at
 com.PS.Main.main(Main.java:11)

ps:driver already installed

Please change the Class.forName("com.mysql.cj.jdbc.Driver"); line like below.

 Class.forName("com.mysql.jdbc.Driver");

Since you are using the version 5 of mysql connector avoid using .cj prefix in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM