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?