Java: Can’t use the “USE” keyword in MySQL?

Java: Can’t use the “USE” keyword in MySQL? … here is a solution to the problem.

Java: Can’t use the “USE” keyword in MySQL?

I have two SQL files:

Query 1 .sql

SELECT * FROM laptop_store.gpu;

Query 2.sql

USE laptop_store;
SELECT * FROM gpu

Performing both in MySQL Workbench 8.0 CE will show the same result:

result:

When I copy everything from two SQL code and run it in java

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

public class NewClass {
    static String queryString1 = "SELECT * FROM laptop_store.gpu";

static String queryString2 = "USE laptop_store;\n" +
                                 "SELECT * FROM gpu";

public static void main(String[] args) {
       try{      
          Class.forName("com.mysql.cj.jdbc.Driver");  
          Connection con = DriverManager.getConnection( 
              "jdbc:mysql://localhost:3306/laptop_store","root","tomnisa123");          

Statement statement = con.createStatement();   

Change SQL code here:
          ResultSet rs = statement.executeQuery(queryString1); 

ResultSetMetaData rsmd = rs.getMetaData();

int colCount = rsmd.getColumnCount();

while(rs.next()) {
                for (int i = 1; i <= colCount; i++){          
                    System.out.print(rs.getString(i) + "  ");
                }
                System.out.println();
            }

con.close();  

} catch(Exception e){ 
        System.out.println(e);
       }  
    }  
}

Only the first one is a success

success .

But the second one shows an error:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM gpu' at line 2

Why can’t I use the “USE” keyword in MySQL?

Related Problems and Solutions