[英]How to resolve the Exception “com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection”?
[英]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();
}
}
错误:
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)
你可以尝试更换
Class.forName("com.mysql.jdbc.Driver");
和
Class.forName("com.mysql.cj.jdbc.Driver");
我认为 MySQL Connector/J 中实现 java.sql.Driver 的类的名称已经从 com.mysql.jdbc.Driver 更改为 com.mysql.cj.jdbc.Driver。
有两个问题:
Class.forName("com.mysql.jdbc.Driver");
- 此 JDBC 驱动程序是旧的,已被指定的新驱动程序取代。 这只是一个警告。 这不是您的问题的原因。 您不需要使用Class.forName
。 只需删除该行。 只要您的类路径中有正确的驱动程序库,就会在您调用DriverManager.getConnection
时使用正确的驱动程序。
这个说法:
结果集 rs = st.executeQuery("查询");
正在尝试执行查询“查询”。 但“查询”不是有效的 SQL 查询。 您需要改用变量名:
ResultSet rs = st.executeQuery(query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.