[英]How to resolve the jdbc connection error ? Why I can't fetch the table data from the mysql server?
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.我认为 MySQL Connector/J 中实现 java.sql.Driver 的类的名称已经从 com.mysql.jdbc.Driver 更改为 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. You do not need to use Class.forName
.您不需要使用
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.只要您的类路径中有正确的驱动程序库,就会在您调用
DriverManager.getConnection
时使用正确的驱动程序。
This statement:这个说法:
ResultSet rs = st.executeQuery("query");结果集 rs = st.executeQuery("查询");
is trying to execute the query "query".正在尝试执行查询“查询”。 But "query" is not a valid SQL query.
但“查询”不是有效的 SQL 查询。 You need to use the variable name instead:
您需要改用变量名:
ResultSet rs = st.executeQuery(query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.