Java SQL expected 6 bytes and received 0 error - java

I am getting this error: "Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated." When I try to connect to my data base. I can not seem to find any solution that works. Could you guys give me a hand?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RetrieveData
{
private String zone;
private String date;
private String userName = "User";
private String password = "Password";
private String serverAdress= "jdbc:derby://Server:1010/Database";
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
RetrieveData(String zoneToPull, String dayToPull)
{
zone = zoneToPull;
date = dayToPull;
}
public int HistoryActual()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(serverAdress, userName, password);
String sql = "SELECT TOP 10 " +
"*" +
"FROM" +
"walks" +
"WHERE"+
"company_id = 'TMS3'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next())
{
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
return 0;
}
}
Here is the stack trace:
java.sql.SQLNonTransientConnectionException: Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at RetrieveData.HistoryActual(RetrieveData.java:27)
at BookToGoals.(BookToGoals.java:34)
at Console.Console(Console.java:96)
at Console.access$0(Console.java:47)
at Console$1.run(Console.java:43)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: ERROR 08006: Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.net.Reply.fill(Unknown Source)
at org.apache.derby.client.net.Reply.ensureALayerDataInBuffer(Unknown Source)
at org.apache.derby.client.net.Reply.readDssHeader(Unknown Source)
at org.apache.derby.client.net.Reply.startSameIdChainParse(Unknown Source)
at org.apache.derby.client.net.NetConnectionReply.readExchangeServerAttributes(Unknown Source)
at org.apache.derby.client.net.NetConnection.readServerAttributesAndKeyExchange(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowServerAttributesAndKeyExchange(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowUSRIDPWDconnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowConnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.(Unknown Source)
at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl.newNetConnection(Unknown Source)
... 22 more

It looks like I found out what is going on. It is due to my own confusion. I am trying to connect to a Microsoft SQL database. Thus I need the sqljdbc driver not derby. This has resolve my issue. Thanks for the help guys.

Related

JDBC connection timed out on Windows 10

This is my code:
public static void main(String[] args) {
System.out.println("Start");
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
Properties properties = new Properties();
properties.put("user", "xxx");
properties.put("password", "xxx");
Connection conn = DriverManager.getConnection("jdbc:db2://xxx.xxx.xxx.xxx:50000/xxxxxx", properties);
Statement stmt = conn.createStatement();
String query = "SELECT DESC_UFF FROM UFFICIO";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("DESC_UFF"));
}
conn.close();
System.out.println("Stop");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
I use a jar file and it works fine on Windows XP and Windows 7, on a different PC, but not on Windows 10.
On Windows 10 I have this error:
Start
com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException: [jcc][t4][2043][11550][4.14.146] Eccezione java.net.ConnectException: errore durante l'apertura del socket sul server /xxx.xxx.xxx.xxx sulla porta 50.000 con il messaggio Connection timed out: connect. ERRORCODE=-4499, SQLSTATE=08001
at com.ibm.db2.jcc.am.ed.a(ed.java:320)
at com.ibm.db2.jcc.am.ed.a(ed.java:338)
at com.ibm.db2.jcc.t4.wb.a(wb.java:434)
at com.ibm.db2.jcc.t4.wb.<init>(wb.java:93)
at com.ibm.db2.jcc.t4.a.b(a.java:354)
at com.ibm.db2.jcc.t4.b.newAgent_(b.java:2030)
at com.ibm.db2.jcc.am.Connection.initConnection(Connection.java:732)
at com.ibm.db2.jcc.am.Connection.<init>(Connection.java:680)
at com.ibm.db2.jcc.t4.b.<init>(b.java:334)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:233)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:199)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:475)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:116)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at main.TestDb2.main(TestDb2.java:20)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.ibm.db2.jcc.t4.w.run(w.java:49)
at java.security.AccessController.doPrivileged(Native Method)
at com.ibm.db2.jcc.t4.wb.a(wb.java:420)
... 13 more
The version of DB2 database is 9.7 and Windows firewall is disabled.
Any suggestion?

How to connect MS Access database with Java 8?

What I am trying to do:
I want to connect my MS Access Database with Java 8. So I am using "UcanAccess" driver to connect to my Database.
What I am using:
Eclipse, Java 8, and MS Access database
My MS Access database path:
C:/Users/dave/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/Database11.accdb"
I have the following Jar files in my project:
mysql-connector-java-5.1.35-bin.jar
ucanaccess-2.095.jar
jackcess-2.1.2.jar
hsqldb.jar
commons-lang3-3.4.jar
commons-logging-1.2.jar
Error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/builder/CompareToBuilder
at com.healthmarketscience.jackcess.impl.RowIdImpl.compareTo(RowIdImpl.java:106)
at com.healthmarketscience.jackcess.impl.IndexData$Entry.compareTo(IndexData.java:2039)
at com.healthmarketscience.jackcess.impl.IndexData$Entry.compareTo(IndexData.java:1847)
at java.util.Collections.indexedBinarySearch(Unknown Source)
at java.util.Collections.binarySearch(Unknown Source)
at com.healthmarketscience.jackcess.impl.IndexData$DataPage.findEntry(IndexData.java:2570)
at com.healthmarketscience.jackcess.impl.IndexData.findEntryPosition(IndexData.java:844)
at com.healthmarketscience.jackcess.impl.IndexData.access$3700(IndexData.java:47)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.updatePosition(IndexData.java:2335)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.restorePosition(IndexData.java:2273)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.restorePosition(IndexData.java:2256)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.beforeEntry(IndexData.java:2218)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findPotentialRow(IndexCursorImpl.java:376)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findFirstRowByEntryImpl(IndexCursorImpl.java:282)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findFirstRowByEntry(IndexCursorImpl.java:153)
at com.healthmarketscience.jackcess.impl.DatabaseImpl$DefaultTableFinder.findRow(DatabaseImpl.java:2074)
at com.healthmarketscience.jackcess.impl.DatabaseImpl$TableFinder.findObjectId(DatabaseImpl.java:1953)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.readSystemCatalog(DatabaseImpl.java:858)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.<init>(DatabaseImpl.java:518)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.open(DatabaseImpl.java:389)
at com.healthmarketscience.jackcess.DatabaseBuilder.open(DatabaseBuilder.java:248)
at net.ucanaccess.jdbc.DefaultJackcessOpener.open(DefaultJackcessOpener.java:38)
at net.ucanaccess.jdbc.DBReference.<init>(DBReference.java:158)
at net.ucanaccess.jdbc.DBReferenceSingleton.loadReference(DBReferenceSingleton.java:57)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:103)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at ex01.main(ex01.java:37)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.builder.CompareToBuilder
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 28 more
code to connect to database:
public class ex01 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/Users/dave/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/Database11.accdb";
Connection con;
Statement stmt;
String query = "Select * from user";
try {
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
// Returns a ResultSet that contains the data produced by the query;
// never null
ResultSet rs = stmt.executeQuery(query);
System.out.println("User Data:");
System.out.println("FirstName\tLastName\tAge");
while (rs.next()) {
String fName = rs.getString("FirstName");
String lName = rs.getString("LastName");
int age = rs.getInt("age");
System.out.println(fName + "\t" + lName + "\t" + age);
}
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
As you can see, jackcess 2.1.2 depends on commons-lang 2.6. The version you use (3.4) is not backward compatible.
Why do you have a JDBC driver for MySQL and for HSQLDB if your goal is to connect to MS Access?

MYSQL - Communications link failure; timeout

The class below creates a connection to my MYSQL user, it then submits some data into a table.. I've checked and double checked the username and password, it's definitely 100% correct, but why does it keep throwing this memory leak? I am having trouble figuring this out myself, I've been reading all the related topics, but none really seems to be the same issue as mine.
package com.rs.MYSQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import com.rs.Settings;
import com.rs.utils.Lottery;
public class LotteryMYSQL {
private static Connection connection;
private static long lastConnection = System.currentTimeMillis();
public static void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://runerebellion.com:3306/database",
"user", "pass");//fake user&pass
} catch (Exception e) {
e.printStackTrace();
}
}
public static void destroyConnection() {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void init() {
createConnection();
}
public static boolean updateInfo() {
try {
if (Settings.DisableMYSQL == true)
return false;
createConnection();
Statement stmt = connection.createStatement();
if (Lottery.getCurrentLotteryWinner() != null)
stmt.executeUpdate("UPDATE info SET moneyEarned = '"
+ Lottery.options.size() + "', lastWinner = '"
+ Lottery.getCurrentLotteryWinner() + "'");
else
stmt.executeUpdate("UPDATE info SET moneyEarned = '"
+ Lottery.options.size() + "', lastWinner = '"
+ Lottery.getLastLotteryWinner() + "'");
destroyConnection();
} catch (Throwable e) {
if (System.currentTimeMillis() - lastConnection > 10000) {
destroyConnection();
createConnection();
lastConnection = System.currentTimeMillis();
}
}
return false;
}
}
The memory leak is below
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(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1137)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:356)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2504)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2541)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2323)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.rs.MYSQL.LotteryMYSQL.createConnection(LotteryMYSQL.java:19)
at com.rs.Launcher.main(Launcher.java:103)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:258)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:306)
... 16 more
Used this:
and it worked fine
Class.forName("com.mysql.jdbc.Driver").newInstance();
String IP = "";
String DB = "";
String User = "";
String Pass = "";
connection = DriverManager.getConnection("jdbc:mysql://" + IP + "/"
+ DB, User, Pass);

java.lang.ClassNotFoundException: org.netezza.Driver

I am trying to connect to a Netezza database using the JDBC driver and do a simple SELECT query. I have the nzjdbc.jar file in the lib folder in my project (using eclipse) and I am getting the following error.
java.lang.ClassNotFoundException: org.netezza.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Tests {
public static void main(String[] args)
{
String server = "myhost.com";
String port = "5480";
String dbName = "dbname";
String url = "jdbc:netezza://" + server + "/" + dbName ;
String user = "user";
String pwd = "pwd";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.netezza.Driver");
System.out.println(" Connecting ... ");
conn = DriverManager.getConnection(url, user, pwd);
System.out.println(" Connected "+conn);
String sql = "SELECT COUNT(*) FROM TABLE";
st = conn.createStatement();
rs = st.executeQuery(sql);
if(rs.next()) {
System.out.println(rs.getString(1));
} else {
System.out.println(" No data found");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if( rs != null)
rs.close();
if( st!= null)
st.close();
if( conn != null)
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
In Eclipse you will need to add the jar to the libraries in your "Build path"
Eclipse documentation
Tutorial

Java serializable object to a file

I have a Swing Program. I am having trouble to save entire main class to a file.
public class GreenHouseMain extends JFrame implements ActionListener,
MouseListener, Runnable, WindowListener, KeyListener, Serializable
{
//.....other components
static GreenHouseMain ghMain;
}
public static void main(String[] args)
{
ghMain = new GreenHouseMain();
}
public void startEvents()
{
suspended = false;
terminate = false;
jbStart.setEnabled(false);
worker = new Thread(new Runnable()
{
public void run()
{
try
{
//Other Code
} catch (ControllerException e)
{
try
{
Date now = new Date();
String log = "";
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("error.log")));
if (e.getMessage() == "Unknown Windows Malfuction")
{
log = "ErrorCode=1, WindowMalfunction," + now;
} else
{
log = "ErrorCode=2, PowerOut," + now;
}
out.println(log);
jTextArea.append(log + "\n");
out.close();
out.flush();
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("dump.out"));
//It failed in here, says "java.lang.NullPointerException
output.writeObject(GreenHouseMain.ghMain);
output.flush();
} catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
});
worker.start();
}
Few things you should know:
1. All classes have been implements Serializable interface
2. There several threads in the program (don't know if it is reason for exception
3. I have had Serialized a object to file before with about the same code but in a console app. Don't know why it fails here.
at javax.swing.plaf.basic.BasicScrollPaneUI.paint(Unknown Source)
at javax.swing.plaf.ComponentUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
This
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
should be:
} catch (IOException ex) {
ex.printStackTrace();
}
This will give you much better information, most importantly the exact line where the NullPointerException occurs and from where that line is reached. If that doesn't make the cause of the problem obvious, start the program in a debugger and put a breakpoint on that line.

Categories