I have two SQL files:
query1.sql
SELECT * FROM laptop_store.gpu;
query2.sql
USE laptop_store;
SELECT * FROM gpu
Excecuting both in MySQL Workbench 8.0 CE will display the same 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 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 I cannot use the "USE" keyword from MySQL?
Apparently, the problem is that you are trying to execute two SQL statements in a single executeQuery
call. You can't do that. Run the "use" in a separate execute
calls.
But the question is why are you using the use
statement?
If you are using it for no particular reasons ... don't.
If you are using it to make sure that you are using the correct database, that is unnecessary. The database / schema to be used is specified in the connection URL.
"jdbc:mysql://localhost:3306/laptop_store" ^^^^^^^^^^^^
If you are using it to dynamically switch between databases / schemas, it may be better to use a separate connection for each database.