JDBC MySQL 次执行 SQL 次失败
JDBC MySQL execute SQL failures
这是我的代码。我在 MySQL 中有一个数据库,用于处理。我提到了与此例外相关的所有问题。但是 none 对我有用。问题出在我使用的查询上。当我将查询设为
SELECT * FROM customers;
然后它工作正常。但是当我将其更新为以下内容时,将抛出异常。
SELECT * FROM customer WHERE customer_id LIKE " + "'%" + consumerId + "%'
这是我遇到的异常。
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1036)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:627)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1013)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.GeneratedConstructorAccessor4.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.smart.data.customer.CustomerInfoProvider.findDetails(CustomerInfoProvider.java:81)
at com.smart.data.customer.CustomerInfoProvider.provideRequiredCustomerDetails(CustomerInfoProvider.java:28)
at com.smart.data.manipulator.Starter.main(Starter.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2914)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:559)
... 22 more
Exception in thread "main" java.lang.NullPointerException
at com.smart.data.customer.CustomerInfoProvider.provideRequiredCustomerDetails(CustomerInfoProvider.java:30)
at com.smart.data.manipulator.Starter.main(Starter.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
package com.smart.data.customer;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: dulithdecozta
* Date: 2/5/15
* Time: 7:20 PM
* To change this template use File | Settings | File Templates.
*/
public class CustomerInfoProvider {
static Logger log = Logger.getLogger(CustomerInfoProvider.class.getName());
ResultSet customerResultSet = null;
Connection conn = null;
public void provideRequiredCustomerDetails(ArrayList customerIdArraylist) {
for (int i = 0; i < customerIdArraylist.size(); i++) {
try {
customerResultSet = findDetails(customerIdArraylist.get(i).toString());
try {
while (customerResultSet.next()) {
try {
System.out.println("Fullname : " + customerResultSet.getString("fullname"));
System.out.println("Consumer ID : " + customerResultSet.getString("customer_id"));
System.out.println("City : " + customerResultSet.getString("city"));
System.out.println("gender : " + customerResultSet.getString("gender"));
System.out.println("Occupation : " + customerResultSet.getString("occupation"));
System.out.println(i);
System.out.println("*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*");
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public ResultSet findDetails(String consumerId) throws IOException {
// Load property file
Properties properties = new Properties();
// Define an input stream
InputStream inputStream = null;
ResultSet rs = null;
try {
inputStream = new FileInputStream("/home/abc/Desktop/Jigi/database.properties"); // Path to the property file
} catch (FileNotFoundException e) {
log.debug("Exception encountered : File Not Found : ");
e.printStackTrace();
}
try {
// load a properties file
properties.load(inputStream);
} catch (IOException e) {
log.debug("Exception encountered : A problem with the Input Stream : ");
e.printStackTrace();
}
conn = null;
Statement stmt = null;
try {
Class.forName(properties.getProperty("JDBC_DRIVER"));
// log.debug("Connecting to database...!!");
conn = DriverManager.getConnection(properties.getProperty("DB_URL"), properties.getProperty("USER"), properties.getProperty("PASS"));
// log.debug("Creating statement...!");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM customer WHERE customer_id LIKE " + "'%" + consumerId + "%'");
} catch (Exception ex) {
ex.printStackTrace();
}
return rs;
}
}
如果我关于您的查询花费时间过长的理论是正确的,那么您需要以某种方式使查询花费更少的时间。
你可以试试
SELECT col1, col2, col3
FROM customer
WHERE customer_id LIKE '" + consumerId + "%'"
LIMIT 10
当您在 LIKE
子句中省略前导 %
时,您允许 MySQL 使用索引来查找正确的行。
当您从查询中枚举所需的列时,您可以减少网络流量并允许 MySQL 在构造查询答案时使用一些效率。
当您说 LIMIT 10
时,您可以避免 MySQL 在您的用户出错并请求空字符串时尝试 return 整个 table 的可能性.
您还应该为 customerId
值使用绑定参数。您可以使用 JDBC.
查看如何执行此操作
更改查询返回的结果没有给出异常。
package com.smart.data.customer;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: dulithdecozta
* Date: 2/5/15
* Time: 7:20 PM
* To change this template use File | Settings | File Templates.
*/
public class CustomerInfoProvider {
static Logger log = Logger.getLogger(CustomerInfoProvider.class.getName());
ResultSet customerResultSet = null;
Connection conn = null;
public void provideRequiredCustomerDetails(ArrayList customerIdArraylist) {
for (int i = 0; i < customerIdArraylist.size(); i++) {
try {
customerResultSet = findDetails(customerIdArraylist.get(i).toString());
try {
while (customerResultSet.next()) {
try {
System.out.println("Fullname : " + customerResultSet.getString("fullname"));
System.out.println("Consumer ID : " + customerResultSet.getString("customer_id"));
System.out.println("City : " + customerResultSet.getString("city"));
System.out.println("gender : " + customerResultSet.getString("gender"));
System.out.println("Occupation : " + customerResultSet.getString("occupation"));
System.out.println(i);
System.out.println("*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*");
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public ResultSet findDetails(String consumerId) throws IOException {
// Load property file
Properties properties = new Properties();
// Define an input stream
InputStream inputStream = null;
ResultSet rs = null;
try {
inputStream = new FileInputStream("/home/abc/Desktop/Jigi/database.properties"); // Path to the property file
} catch (FileNotFoundException e) {
log.debug("Exception encountered : File Not Found : ");
e.printStackTrace();
}
try {
// load a properties file
properties.load(inputStream);
} catch (IOException e) {
log.debug("Exception encountered : A problem with the Input Stream : ");
e.printStackTrace();
}
conn = null;
Statement stmt = null;
try {
Class.forName(properties.getProperty("JDBC_DRIVER"));
// log.debug("Connecting to database...!!");
conn = DriverManager.getConnection(properties.getProperty("DB_URL"), properties.getProperty("USER"), properties.getProperty("PASS"));
// log.debug("Creating statement...!");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM customer WHERE customer_id=" +consumerId);
} catch (Exception ex) {
ex.printStackTrace();
}
return rs;
}
}
您可以将这些数据保存到数组列表中,并在需要时调用该列表。这将帮助您防止此异常。这是由于查询的响应时间短。
这是我的代码。我在 MySQL 中有一个数据库,用于处理。我提到了与此例外相关的所有问题。但是 none 对我有用。问题出在我使用的查询上。当我将查询设为
SELECT * FROM customers;
然后它工作正常。但是当我将其更新为以下内容时,将抛出异常。
SELECT * FROM customer WHERE customer_id LIKE " + "'%" + consumerId + "%'
这是我遇到的异常。
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1036)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:627)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1013)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.GeneratedConstructorAccessor4.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.smart.data.customer.CustomerInfoProvider.findDetails(CustomerInfoProvider.java:81)
at com.smart.data.customer.CustomerInfoProvider.provideRequiredCustomerDetails(CustomerInfoProvider.java:28)
at com.smart.data.manipulator.Starter.main(Starter.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2914)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:559)
... 22 more
Exception in thread "main" java.lang.NullPointerException
at com.smart.data.customer.CustomerInfoProvider.provideRequiredCustomerDetails(CustomerInfoProvider.java:30)
at com.smart.data.manipulator.Starter.main(Starter.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
package com.smart.data.customer;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: dulithdecozta
* Date: 2/5/15
* Time: 7:20 PM
* To change this template use File | Settings | File Templates.
*/
public class CustomerInfoProvider {
static Logger log = Logger.getLogger(CustomerInfoProvider.class.getName());
ResultSet customerResultSet = null;
Connection conn = null;
public void provideRequiredCustomerDetails(ArrayList customerIdArraylist) {
for (int i = 0; i < customerIdArraylist.size(); i++) {
try {
customerResultSet = findDetails(customerIdArraylist.get(i).toString());
try {
while (customerResultSet.next()) {
try {
System.out.println("Fullname : " + customerResultSet.getString("fullname"));
System.out.println("Consumer ID : " + customerResultSet.getString("customer_id"));
System.out.println("City : " + customerResultSet.getString("city"));
System.out.println("gender : " + customerResultSet.getString("gender"));
System.out.println("Occupation : " + customerResultSet.getString("occupation"));
System.out.println(i);
System.out.println("*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*");
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public ResultSet findDetails(String consumerId) throws IOException {
// Load property file
Properties properties = new Properties();
// Define an input stream
InputStream inputStream = null;
ResultSet rs = null;
try {
inputStream = new FileInputStream("/home/abc/Desktop/Jigi/database.properties"); // Path to the property file
} catch (FileNotFoundException e) {
log.debug("Exception encountered : File Not Found : ");
e.printStackTrace();
}
try {
// load a properties file
properties.load(inputStream);
} catch (IOException e) {
log.debug("Exception encountered : A problem with the Input Stream : ");
e.printStackTrace();
}
conn = null;
Statement stmt = null;
try {
Class.forName(properties.getProperty("JDBC_DRIVER"));
// log.debug("Connecting to database...!!");
conn = DriverManager.getConnection(properties.getProperty("DB_URL"), properties.getProperty("USER"), properties.getProperty("PASS"));
// log.debug("Creating statement...!");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM customer WHERE customer_id LIKE " + "'%" + consumerId + "%'");
} catch (Exception ex) {
ex.printStackTrace();
}
return rs;
}
}
如果我关于您的查询花费时间过长的理论是正确的,那么您需要以某种方式使查询花费更少的时间。
你可以试试
SELECT col1, col2, col3
FROM customer
WHERE customer_id LIKE '" + consumerId + "%'"
LIMIT 10
当您在 LIKE
子句中省略前导 %
时,您允许 MySQL 使用索引来查找正确的行。
当您从查询中枚举所需的列时,您可以减少网络流量并允许 MySQL 在构造查询答案时使用一些效率。
当您说 LIMIT 10
时,您可以避免 MySQL 在您的用户出错并请求空字符串时尝试 return 整个 table 的可能性.
您还应该为 customerId
值使用绑定参数。您可以使用 JDBC.
更改查询返回的结果没有给出异常。
package com.smart.data.customer;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: dulithdecozta
* Date: 2/5/15
* Time: 7:20 PM
* To change this template use File | Settings | File Templates.
*/
public class CustomerInfoProvider {
static Logger log = Logger.getLogger(CustomerInfoProvider.class.getName());
ResultSet customerResultSet = null;
Connection conn = null;
public void provideRequiredCustomerDetails(ArrayList customerIdArraylist) {
for (int i = 0; i < customerIdArraylist.size(); i++) {
try {
customerResultSet = findDetails(customerIdArraylist.get(i).toString());
try {
while (customerResultSet.next()) {
try {
System.out.println("Fullname : " + customerResultSet.getString("fullname"));
System.out.println("Consumer ID : " + customerResultSet.getString("customer_id"));
System.out.println("City : " + customerResultSet.getString("city"));
System.out.println("gender : " + customerResultSet.getString("gender"));
System.out.println("Occupation : " + customerResultSet.getString("occupation"));
System.out.println(i);
System.out.println("*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*");
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public ResultSet findDetails(String consumerId) throws IOException {
// Load property file
Properties properties = new Properties();
// Define an input stream
InputStream inputStream = null;
ResultSet rs = null;
try {
inputStream = new FileInputStream("/home/abc/Desktop/Jigi/database.properties"); // Path to the property file
} catch (FileNotFoundException e) {
log.debug("Exception encountered : File Not Found : ");
e.printStackTrace();
}
try {
// load a properties file
properties.load(inputStream);
} catch (IOException e) {
log.debug("Exception encountered : A problem with the Input Stream : ");
e.printStackTrace();
}
conn = null;
Statement stmt = null;
try {
Class.forName(properties.getProperty("JDBC_DRIVER"));
// log.debug("Connecting to database...!!");
conn = DriverManager.getConnection(properties.getProperty("DB_URL"), properties.getProperty("USER"), properties.getProperty("PASS"));
// log.debug("Creating statement...!");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM customer WHERE customer_id=" +consumerId);
} catch (Exception ex) {
ex.printStackTrace();
}
return rs;
}
}
您可以将这些数据保存到数组列表中,并在需要时调用该列表。这将帮助您防止此异常。这是由于查询的响应时间短。