skip to Main Content

I’m trying to use MySQL and jdbc, but I can’t use the executeQuery command, do you know why?
It’s the first time I’ve programmed in Java and integrated SQL into the program, I don’t know what’s wrong.

enter image description here

import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;

public class Main {
    public static void main(String[] args) {
        //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
        // to see how IntelliJ IDEA suggests fixing it.
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc-book", "root","root");
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery();
        //("select * from published_books");
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    Problem solved! All it took was a change to the import statements, replacing java.beans.Statement with java.sql.Statement. And add a try-catch.

    import java.sql.Statement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    
    public class Main {
        public static void main(String[] args) {
            try{
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc-book", "root", "root");
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery("select * from published_books");
    
                while (resultSet.next()) {
                    System.out.println(resultSet.getString("title"));
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    

  2. First, you have to download mysql-connector-java.jar into the project sturcture in Intellij. and add Class.forname("com.mysql.cj.jdbc.Driver") into the code

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    import java.sql.ResultSet;
    
    public class Main{
    
     public static void main(String[] args){
        try{
            //This is the necessary part you have missed
            Class.forname("com.mysql.cj.jdbc.Driver");
    
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc-book","root","root");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from published_books");
    
            while (resultSet.next()) {
                System.out.println(resultSet.getString("title"));
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search