[英]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.