import com.mysql.jdbc.Driver;
import java.sql.*;
public class JdbcDemo {
public static class jdbcTest
{
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/coffee_db";
String uname = "Jeep";
String pass = "random";
String query = "select * from customers;";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,uname,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("query");
while (rs.next()) {
String name = rs.getString("first_name");
System.out.println(name);
}
st.close();
con.close();
}
}
Error:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Exception in thread "main" java.sql.SQLException: Statement.executeQuery() cannot issue statements that do not produce result sets.
at enter code herecom.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1135)
at com.company.JdbcDemo$jdbcTest.main(JdbcDemo.java:22)
Can you try and replace
Class.forName("com.mysql.jdbc.Driver");
with
Class.forName("com.mysql.cj.jdbc.Driver");
I think that the name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver.
There are two issues:
Class.forName("com.mysql.jdbc.Driver");
- this JDBC driver is old and has been replaced by the stated new one. This is only a warning. This is not the cause of your problem. You do not need to use Class.forName
. Just remove that line. The correct driver will be used when you call DriverManager.getConnection
, as long as you have the correct driver library in your classpath.
This statement:
ResultSet rs = st.executeQuery("query");
is trying to execute the query "query". But "query" is not a valid SQL query. You need to use the variable name instead:
ResultSet rs = st.executeQuery(query);
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.