I have written a Java Program and the program connects to a database on my server, to find records, write records, update and delete. for some reason finding records works, but most of the time when i try to save or write a record it gives an error message saying:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 9,787 milliseconds ago. The last packet sent successfully to the server was 8,183 milliseconds ago.
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:2552)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3002)
... 46 more
Can anyone explain why this is happening?
Usuually this gives me the error message when trying to add a record, after i had the software running for more than about half a minute. seems to loose connection or something. when i run the program and quickly write a new record, it works
I was having the same sort of issue. I referred many post and comments but the thing worked for me was changing some parameters of the my.cnf file. Hope it will help you also ....
Set following parameters in my.cnf [mysqld] section
interactive_timeout=180 # "No.of sec. a server waits for activity on interactive connection before closing it"
wait_timeout=180 # "No. of sec. a server waits for an activity on a connection before closing it"
max_connect_errors=9999 # "More than this number of interrupted connections from a host this host will be blocked from further connections"
skip-name-resolve # "Don't resolved host names. All host names are IP's"
Sometimes this problem comes due to size of system RAM.May be you are inserting the data using buffer through RAM. To get out of this problem.
Set the Auto commit disable before inserting the data.
insert some amount of data appropriate to your System RAM (not the
whole).
Commit the query.
Do the steps 2 and 3 again until the whole insertion will not be
done.
You can understand this by the following code.
public static void main(string args[])
{
Connection con = null;
Statement stm = null;
int i;
float ratio;
ratio=1.0f;
try
{
Class.forName("com.mysql.jdbc.Driver");
// Connecting to the database
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo",
"ashish", "impetus");
File f = new File("filler"); // taking the random text data from the file
// filler.txt and inserting that string
// in filler field of the relations
RandomAccessFile r = new RandomAccessFile(f,"r");
Random randomGenerator = new Random();
String strLine=new String();
int r1,flag=0;
stm = con.createStatement();
con.setAutoCommit(false) ;
int k=0;
i=0;
long sum2=0;
while(k%50000==0)
{
final long start = currentTimeMillis();
final StringBuilder builder =
new StringBuilder("INSERT INTO accounts
(aid, bid,abalance,filler) VALUES ");
while(i!=naccounts*ratio*scale )
{
int j=i+1;
for(int l=0;l<40;l++)
{
strLine+=((char)r.read());
r.skipBytes(0);
}
r1=randomGenerator.nextInt(1500);
if(strLine.equals(""))
{
flag=1;
}
if(flag!=1)
{
strLine=strLine.replaceAll("\\s","");
strLine=strLine.replaceAll("\\t","");
}
flag=0;
if (i%50000!=0)
{
builder.append(",");
}
builder.append(format("(%s, %s, %s, '%s')", j,
i/naccounts+1, 0, strLine));
strLine="";
r.seek(r1);
i++;
if(i%50000==0||i>=naccounts*ratio*scale)
{
final String query = builder.toString();
final PreparedStatement statement1 = con.prepareStatement(query);
statement1.execute();
con.commit();
final long stop= currentTimeMillis();
sum2=sum2+(stop-start);
statement1.close();
}
if(i%50000==0||i>=naccounts*ratio*scale)
{
break;
}
}
k=k+50000;
if(k>naccounts*ratio*scale)
{
break;
}
}
System.out.println(i+" rows inserted accounts table ");
System.out.println("time taken = "+sum2+" milliseconds");
}
catch (SQLException e)
{
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
catch (Exception e)
{
e.printStackTrace();
}
}
Did you follow/read this tutorial :
Connectivity with MYSQL
You have a part for your exception which can be useful for you.
I will quote something about your specific exception, just try that :
If you get a SQLException: Connection refused or Connection timed out
or a MySQL specific CommunicationsException: Communications link
failure, then it means that the DB isn't reachable at all. This can
have one or more of the following causes:
IP address or hostname in JDBC URL is wrong. Hostname in JDBC URL is
not recognized by local DNS server. Port number is missing or wrong in
JDBC URL. DB server is down. DB server doesn't accept TCP/IP
connections. DB server has run out of connections. Something in
between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping. Refresh DNS or use IP address in JDBC
URL instead. Verify it based on my.cnf of MySQL DB. Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes
connections in finally. Disable firewall and/or configure
firewall/proxy to allow/forward the port.
Related
I made a fairly small java program in netbeans, with the database saved in the scr folder under database/mainUserData, On my main pc, if i export it to a .jar folder, It works, If i copy all the data in the folder (70mb's worth) to another pc, it can't find the database any more, I made sure to add code that always uses the current directory in the jar folder as a url to the database, this is the connection code:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", "jacovanstryp", "Password1234");
Why is it when i move it to another computer (The whole file, it no longer knows where the database is?
What I have Tried:
URL url = this.getClass().getResource("/com/vanstryp/res/Database/MainUserData"); // This is the same directory as where the .jar is located
This just returns Null.
This is the top Error code it returns
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused: connect.
This is the code for the method I used
public boolean checkLogin(String username, String password) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//This code will connect the database to the java program
//Information to connect database obtained from --> https://www.youtube.com/watch?v=c7RZV4VLv3s
Connection myconObj = null; //allows to connect to database
Statement mystatObj = null; // create statement (Execute queries)
ResultSet myresObj = null; // get result
ResultSetMetaData mymeta = null;
try {
String query = "select * from JACOVANSTRYP.MAINUSERDATA";
URL databaseLocation = this.getClass().getResource("/com/vanstryp/database/MainUserData/");
myconObj = DriverManager.getConnection("jdbc:derby:/" + databaseLocation, "jacovanstryp", "Eduplex1234");
mystatObj = myconObj.createStatement();
myresObj = mystatObj.executeQuery(query);
mymeta = myresObj.getMetaData();
int colomnNo = mymeta.getColumnCount();
while (myresObj.next()) {
String dbUsername = myresObj.getString("Username");
String dbPassword = myresObj.getString("Password");
System.out.println();
if (username.equalsIgnoreCase(dbUsername) && password.equals(dbPassword)) {
PrintWriter activeUser = new PrintWriter(new FileWriter("activeUser.db"));
activeUser.println(dbUsername);
activeUser.close();
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
} catch
(ClassNotFoundException ex) {
Logger.getLogger(commonMethods.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
This line:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", ...);
uses a connection string of "jdbc:derby://localhost:1527/MainUserData". That means that you have setup (maybe through Netbeans) a Derby server on that computer listening on port 1527.
Copying a jar and the file backing the database is not enough: you must start the Derby server on the new host or use the one from the old host:
myconObj = DriverManager.getConnection("jdbc:derby://other.host.full.name:1527/MainUserData", ...);
Alternatively, you could use the embedded mode of Derby. Then you just have to declare which folder contains the database file:
myconObj = DriverManager.getConnection("jdbc:derby:/path/to/MainUserData", ...);
In this mode, you can just copy both the jar (and its optional other files) and the database to the new system, and it should find the database if you give a correct path.
I'm developing a web app that uses app engine (java) as a backend. I need the backend to listen for received transactions and broadcast transactions on the bitcoin network. I have bitcoinj set up to handle this functionality but I can't seem to get the blockstore object initialize.
Bitcoinj allows me to use mysql to store blocks. The connection is set up like this:
public static void getBlockStore(){
int fullStoreDepth = 1000;
String db = "databasename";
String un = "root";
String pw = "";
String host = "/cloudsql/database-instance-id";//I have also used the ip address, but it didn't work
try {
blockStore = new MySQLFullPrunedBlockStore(network, fullStoreDepth, host, db, un, pw);
logger.info("Blockstore created is " + blockStore);
} catch (BlockStoreException e) {
logger.info("Blockstore error " + e);
}
}
But in the backend I receive a connection error when trying to connect to my database. I don't have or don't know which port to connect to. The other information is all correct. I have tried with another mysql db from godaddy but I got the same error.
How can I get connected to a mysql database either in cloud sql or a normal mysql database?
I am working on a modbus TCP implementation in Java. I've tried 3 different libraries so far modbus4j, jamod, and j2mod. I can successfully access my slave device with the linux modpoll tool: http://www.modbusdriver.com/modpoll.html
michael#michael-G75VW:~/Documents/modbus-test-tool/linux$ ./modpoll -a255 -r1 -1 192.168.1.101
modpoll 3.4 - FieldTalk(tm) Modbus(R) Master Simulator
Copyright (c) 2002-2013 proconX Pty Ltd
Visit http://www.modbusdriver.com for Modbus libraries and tools.
Protocol configuration: MODBUS/TCP
Slave configuration...: address = 255, start reference = 1, count = 1
Communication.........: 192.168.1.101, port 502, t/o 1.00 s, poll rate 1000 ms
Data type.............: 16-bit register, output (holding) register table
-- Polling slave...
[1]: 256
This causes the barrier on my device to go up which is great. However, working in the Java implementation I am unable to reproduce this. I've tried many different steps but all fail. In J2mod/jamod I continually get a invalid slaveId error when using '255' which is the unit id i use in the above command. If I use anything else, I get a CRC failed error. In mod4j I get various errors including error code = 4. Here is my latest J2mod code which returns either CRC error (if not 255) or invalid slaveId. I know slaveId is mostly used for Serial communications, but my device only responds to a Unit ID of 255 when using other applications.
Integer value = Integer.decode(val).intValue();
Integer unitID = Integer.decode(uid).intValue();
Integer length = Integer.decode(len).intValue();
Integer ref = Integer.decode(reference).intValue();
SimpleRegister MyReg = new SimpleRegister(value);
try {
InetAddress address;
address = InetAddress.getByName(addr);
//2. Open the connection
TCPMasterConnection con = new TCPMasterConnection(address);
con.setPort(port);
con.connect();
//3. Prepare the requestWrite
WriteSingleRegisterRequest WriteReq = new WriteSingleRegisterRequest(ref,MyReg);
WriteReq.setDataLength(length);
WriteReq.setUnitID(unitID);
//4. Prepare the transaction
ModbusTCPTransaction trans = new ModbusTCPTransaction(con);
trans.setRequest(WriteReq);
trans.setRetries(0);
trans.execute();
Log.d(TAG, "Complete: " +trans.toString());
return trans.getResponse().getHexMessage();
} catch (UnknownHostException e) {
Log.d(TAG, "UnknownHostException: " + e.getMessage());
return e.getMessage();
} catch (Exception e) {
Log.d(TAG,"Exception: " + e.toString());
return e.getMessage();
}
My manual for the modbus interface is available here:
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CCsQFjAA&url=http%3A%2F%2Fwww.ac-magnetic.com%2Fgermany%2Fsites%2Fdefault%2Ffiles%2F58150001EN_00_Technical%2520Maunal%2520EM01.pdf&ei=Z1dxUv7qF4a9yAGpooHYBQ&usg=AFQjCNGGZnBx_A0fFjuW3qqgWjhS_ek-0w&bvm=bv.55617003,d.aWc
I can't speak to why, exactly, this is happening. I can tell you that both jamod and j2mod (j2mod is a bug-fixed fork of jamod) simply copy whatever you set as the unit number to the 7th byte of the TCP packet. It's then up to the PLC to respond to the packet, as sent.
For j2mod, setting the system property com.ghgande.modbus.debug equal to "true" from the JVM command line will enable debug messages. That will allow you to view a packet dump that should tell you what's happening.
You do make one very interesting comment, and that is that you are seeing CRC errors. You are aware that Modbus/TCP doesn't use a CRC at all?
I am trying to get a connection to a SQLite database (using Eclipse on Windows 8). Everything workes fine as long as the path name doesn't contain any special characters (like "é"). I tried to convert it to UTF-8 (because I read on http://www.sqlite.org/c3ref/open.html that it should be), but it didn't work. I get an "out of memory" exception (SQLException) what means that no database file was found.
This is the code summary of what I did:
public static String DB_PATH = "jdbc:sqlite:" + System.getProperty("user.home") + "<Rest of the path><databasename>.sqlite";
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(DB_PATH);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
// work with the database ...
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
// try to disconnect
// ...
}
Thanks for your help!
Use the latest lib from http://www.xerial.org/maven/repository/artifact/org/xerial/sqlite-jdbc/
I am connecting to MySQL in Java with Connector/J using Named Pipes. My connection and query are successful, but I am receiving a warning when I try to close the connection. I would like to know what I should do to fix whatever is causing the warning other than removing connection.close() (or removing the try-with-resources connection block and not adding a connection.close()).
Here is my code for the query:
public static List<List> QueryDB(int RowValue) {
List<Long> ValueList = new ArrayList();
try {
try (Connection Connection_T = MySQLConnectionResources.createConnection()) {
try (Statement Statement_T = Connection_T.createStatement()) {
String String_T = "SELECT AColumn FROM ATable WHERE BColumn = " + RowValue + ";";
try (ResultSet ResultSet_T = Statement_T.executeQuery(String_T)) {
while (ResultSet_T.next()) {
ValueList.add(ResultSet_T.getLong("AColumn"));
}
}
}
}
} catch(SQLException SQLException_P) {
System.err.println("ERROR: Failed to query the database.");
ValueList.clear();
}
List<List> Result_M = new ArrayList();
Result_M.add(ValueList);
return Result_M;
}
"MySQLConnectionResources" is just a custom class with method "createConnection()". There is nothing special to the class/method; it just creates and returns a connection.
After the method is completed (or technically, after the Java 7 try-with-resources connection block is completed) I receive the following error/warning:
Thu Sep 22 00:31:54 EDT 2011 WARN: Caught while disconnecting...
EXCEPTION STACK TRACE:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Socket is not connected
STACKTRACE:
java.net.SocketException: Socket is not connected
at java.net.Socket.shutdownInput(Socket.java:1456)
at com.mysql.jdbc.MysqlIO.quit(MysqlIO.java:1687)
at com.mysql.jdbc.ConnectionImpl.realClose(ConnectionImpl.java:4368)
at com.mysql.jdbc.ConnectionImpl.close(ConnectionImpl.java:1557)
at ... my class/method here (my class.java:#)
** END NESTED EXCEPTION **
If I remove the try-with-resources block (and don't add a connection.close()), the warning never appears. Also, if I switch to a TCP/IP connection the error never appears. BUT, neither of these solutions are satisfactory for my case. I want to ensure that the connection is properly closed and I will be using named pipe connections.
Any ideas?
-- (edit) --
Also: The error is being thrown by the Log within Connector/J. My error catching has nothing to do with how the error is being caught and printed. I've tried to research how to disable the WARN problems and have it print out just SEVERE problems (within Connector/J's Log), but I was unsuccessful. Furthermore, I would like to fix the WARN problem rather than ignore/conceal it.
-- (edit 2) --
I monitored the MySQL database and the connections aren't being closed. If I use a TCP/IP connection string rather than my named pipe connection string (and don't change anything else) the connection is closed just fine.
-- (edit 3) --
Ignoring my original code... just try the code below and it throws the warning. Seems like a bug to me.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public final class main {
public static void main(String[] args) {
Connection conn = null;
try {
conn =
DriverManager.getConnection("jdbc:mysql:///database?socketFactory=com.mysql.jdbc.NamedPipeSocketFactory&namedPipePath=\\\\.\\Pipe\\mysql.sock",
"root", "password");
conn.close();
} catch (SQLException ex) {
// handle any errors
}
}
}
As it appears to be a bug, I have submitted an official bug report to the MySQL bugs forum.
I will post back here whenever I receive an update.
UPDATE:
My bug report was analyzed by MySQL coders. They believe it is a JAVA bug.
Bug Report