This is my code used to access the value from redis Q.
Jedis jedis = null;
try
{
int maxActive = 1000;
int maxIdle = 5;
int minIdle = 1;
long maxWait = 5000;
JedisPoolConfig config = new JedisPoolConfig ();
config.setMaxActive (maxActive);
config.setMaxIdle (maxIdle);
config.setMinIdle(minIdle);
config.setMaxWait (maxWait);
config.setTestOnBorrow (false);
pool = new JedisPool (config, RedisServerURL) ;
jedis = pool.getResource();
jedis.getClient().setTimeoutInfinite();
redisQMesssage = jedis.rpop(RedisQ);
//my code
}
catch (Exception e)
{
e.printStackTrace();
}
finally{
pool.returnResource(jedis);
pool.destroy();
}
I have the above code in 3 worker threads. i'm calling the 3 worker thread for 40 times(totally).
Rarely 1/5 times i'm getting the error "Could not get a resource from the pool(SocketTimeoutException:)"
Stack trace is
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:22)
at Workers.Worker1.met1(Worker1.java:124)
at Workers.Worker1.work(Worker1.java:108)
at org.gearman.impl.worker.WorkerConnectionController$3.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: connect timed out
at redis.clients.jedis.Connection.connect(Connection.java:124)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:54)
at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1657)
at redis.clients.jedis.JedisPool$JedisFactory.makeObject(JedisPool.java:63)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1188)
at redis.clients.util.Pool.getResource(Pool.java:20)
... 6 more
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(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 redis.clients.jedis.Connection.connect(Connection.java:119)
... 11 more
Please help me out.
Related
I'm using Java to check the response of a url I pass in. This is the current code I'm using. However, I keep getting a connection refused error. I'm testing with the basic Google home page so that I know the rough draft of my code works.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class connectTest {
public static void main(String[] args)
{
boolean test = pageExists();
}
public static boolean pageExists(){
int returnCode= 0;
try {
HttpURLConnection.setFollowRedirects(false);
String httpsURL = "https://www.google.com/";
URL testUrl = new URL(httpsURL);
HttpsURLConnection con =
(HttpsURLConnection)testUrl.openConnection();
returnCode= con.getResponseCode();
System.out.println(returnCode);
} catch (Exception e) {
e.printStackTrace();
}
if (returnCode== HttpURLConnection.HTTP_OK){
return true;
}
else if (returnCode== HttpURLConnection.HTTP_BAD_REQUEST || returnCode==
HttpURLConnection.HTTP_NOT_FOUND ){
return false;
}
else
{
System.out.println("The return code was not 200,400 or 404");
return false;
}
}
}
This is the error I get when I run the following:
java.net.ConnectException: Connection refused: 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 sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
i'm new in java.
I'm trying to connect mysql DB in java
i've got this
mysql.java file:
package program;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class mysql {
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://mysql.cba.pl:3306/dbname";
private static final String USERNAME = "login";
private static final String PASSWORD = "pass";
private static final String MAX_POOL = "250";
private Connection connection;
private Properties properties;
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
main java file:
package program;
public class main {
public static void main(String[] args){
mysql db = new mysql();
db.connect();
}
}
and i'm getting following errors
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
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)
at komunikator.mysql.connect(mysql.java:31)
at komunikator.main.main(main.java:7)
I downloaded ojdbc6-11.2.0.2.0.jar and put in my project folder, after that i add library from jar file.
What i'm doing wrong ?
I'm really new in java so i hope somebody can help me as well :)
I'm using Eclipse Standard/SDK
Version: Kepler Release
Build id: 20130614-0229
ou need to use com.mysql.jdbc_5.1.5 driver for mysql connection and paste jar file in to WEB-INF>Lib folder and use the path of jar file into property>buildpath and use external jar.
it will be a normal desktop application
ok, i changed it on com.mysql.jdbc_5.1.5 driver, i paste this in project path with others .java files and added like u said in properties.
Now i'm getting this:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
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:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2104)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
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:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at program.mysql.connect(mysql.java:32)
at program.main.main(main.java:7)
Caused by: java.net.ConnectException: Connection refused: 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:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2027)
... 13 more
Is mysql.java file correct ?
Edit:
i tried change this
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
on
"com.mysql.jdbc_5.1.5.Driver"
and i am gettin some less errors
java.lang.ClassNotFoundException: com.mysql.jdbc_5.1.5.Driver
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)
at program.mysql.connect(mysql.java:31)
at program.main.main(main.java:7)
Ok, almost i've got this. One thing more.
When im trying connect to on-line DB i got this:
SQLException: 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.
SQLState: 08S01
VendorError: 0
on localhost DB (xamp) it's working fine
what is going on ?
I'm trying to create an multithreaded app (Java) in which some threads insert further rows to database. I use Embedded Derby from JDK.
This is code that concerns establishing connection to database and inserting.
public class DatabaseConnection
{
private static String dbURL = "jdbc:derby:./Database/DB;create=true;user=fafejs;password=fafejs";
private Connection conn;
private DatabaseUpdateContent duc;
private DatabaseUpdateView duv;
public synchronized void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); // load the driver
conn = DriverManager.getConnection(dbURL); // make Derby JDBC connection
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println(conn);
}
catch (Exception except) // TODO - obsluga
{
except.printStackTrace();
}
}
public synchronized void recreateConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection(dbURL);
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println("Reconnect:" + conn);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean updatePlayer(PlayerService player)
{
try
{
int ID = player.getID();
String firstName = player.getFirstName();
String lastName = player.getLastName();
Date birthdate;
if(!(player.getDate() == null))
birthdate = new java.sql.Date(player.getDate().getTime());
else
birthdate = null;
String league = newLeagueName(player.getLeagueName()).toUpperCase();
String team = player.getTeamName();
int apps = player.getApps();
int firstSquad = player.getFirstSquad();
int minutes = player.getMinutes();
int goals = player.getGoals();
int yellowCards = player.getYellowCards();
int redCards = player.getRedCards();
duc.updatePlayersTable(ID, firstName, lastName, birthdate);
duc.updateLeagueTable(league, ID, team, apps, firstSquad, minutes, goals, yellowCards, redCards);
return true;
}
catch (SQLException sqlExcept)
{
//shutdown();
sqlExcept.printStackTrace();
return false;
}
}
public synchronized void shutdown()
{
try
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
//System.gc();
}
catch (SQLException sqlExcept)
{
//sqlExcept.printStackTrace();
}
}
}
public void updatePlayersTable(int ID, String firstName, String lastName, Date birthdate) throws SQLException // z klasy DatabaseUpdateContent
{
PreparedStatement pstmt = conn.prepareStatement("UPDATE APP.PLAYERS SET FIRST_NAME = ?, LAST_NAME = ?, BIRTHDATE = ? WHERE ID = ?");
pstmt.setString(1,firstName);
pstmt.setString(2,lastName);
pstmt.setDate(3,birthdate);
pstmt.setInt(4,ID);
if(pstmt.executeUpdate() == 0)
{
pstmt = conn.prepareStatement("INSERT INTO APP.PLAYERS VALUES (?,?,?,?)");
pstmt.setInt(1, ID);
pstmt.setString(2, firstName);
pstmt.setString(3, lastName);
pstmt.setDate(4, birthdate);
pstmt.execute();
}
pstmt.close();
}
public void updateDB() // procedura, która zajmuje się aktualizacją zawartości bazy danych
{
DatabaseConnection database = new DatabaseConnection();
database.createConnection();
for(PlayerService player: players)
{
while(!database.updatePlayer(player))
{
database.recreateConnection();
}
}
database.shutdown();
}
On the whole, strongly most rows are inserted to appropriate table properly, but sometimes i get SQLNonTransientConnectionException:
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updateLeagueTable(DatabaseUpdateContent.java:39)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:68)
at DataService.TeamService.updateDB(TeamService.java:66)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:35)
at DataService.TeamService.updateDB(TeamService.java:69)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
This exception occurs many times in a row, because if updating player fails, function updatePlayer will return false and we repeat loop in function updateDB. But after a while (about 50 attempts of inserting row), it's possible to establish connection and insert a row.
Certainly i've looked for solution of this problem. I tried way associated with System.gc(), what is suggested in some documentation but it doesn't help in my case.
I was considering also fact that my problem could be connected with multithreading of my app but in Embedded Derby's documentation they say in short that Embedded Derby should deal with it.
Thanks for your support in advance.
EDIT
This is error information that I get after adding code from http://wiki.apache.org/db-derby/UnwindExceptionChain:
----- SQLException -----
SQLState: 08003
Error Code: 40000
Message: No current connection.
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updatePlayersTable(DatabaseUpdateContent.java:17)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:73)
at DataService.TeamService.updateDB(TeamService.java:64)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:39)
at DataService.TeamService.updateDB(TeamService.java:67)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
It seems to me that error associated with not finding database (to be more precise, I mean problem connected with loading the driver of Embedded Derby) is caused by SQLNonTransientConnectionException and there is the rub.
I'm trying to connect to my sql server 21014 using java 8. But i'm getting error.
import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class DBConnec
{
public static void main(String a[])
{
try
{
String url = "jdbc:jtds:sqlserver//localhost:1433/dictionary";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(url);
System.out.println("connection created");
Statement st=conn.createStatement();
String sql="select * from data where word LIKE 'hi'";
ResultSet rs=st.executeQuery(sql);
if (rs.next())
{
System.out.println(rs.getString(0));
}
if(st!=null)
st.close();
if(conn!=null)
conn.close();
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Exception i'm getting is:
java.sql.SQLException: The syntax of the connection URL 'jdbc:jtds:sqlserver//localhost:1433/dictionary' is invalid.
at net.sourceforge.jtds.jdbc.Driver.setupConnectProperties(Driver.java:241)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:181)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnec.main(DBConnec.java:15)
I'm running my code using this command:
java -cp .;"C:\Program Files\Java\jdk1.8.0_66\jre\lib\ext\jtds-1.3.0.jar" DBConnec
I've also tried url without writing "sqlserver". But it gives same exception.
Please help.. Thank you..
I've corrected my syntax but now i'm getting exception like this:
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:434)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:183)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnec.main(DBConnec.java:15)
Caused by: java.net.ConnectException: Connection refused: 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 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
Try this:
String url = "jdbc:jtds:sqlserver://localhost:1433/dictionary";
You missed the colon after sqlserver.
You should not be adding JDBC driver JARs to the jre/lib/ext directory. Learn how to use CLASSPATH properly.
The url format for JTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So your url should be like:
String url = "jdbc:jtds:sqlserver://localhost:1433/dictionary";
^^^____missing colon
I am learning RMI and I made a basic program that uses codebase.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements sInterface,s2int {
public void go()
{
System.out.println("GO");
}
public void doIt()
{
}
public static void main(String[] args)
{
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new SecurityManager());
}
try
{
System.setProperty("java.rmi.server.hostname","helios");
String s = "SERVER";
Registry r = LocateRegistry.getRegistry();
sInterface stub = (sInterface) UnicastRemoteObject.exportObject(new Server(),0);
r.rebind(s,stub);
}catch(Exception x){x.printStackTrace();}
}
}
Client:
public class Client {
public static void main(String[] args)
{
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new SecurityManager());
}
try{
String name = "SERVER";
Registry r = LocateRegistry.getRegistry(args[0]);
sInterface inf = (sInterface)r.lookup(name);
inf.go();
}catch(Exception x)
{
x.printStackTrace();
}
}
}
Client does not have 's2int' interface and that is downloaded from the codebase.
The commands used to start the server and the client modules are as follows:
java -Djava.rmi.server.codebase=http://helios/~owner/rmi.jar
-Djava.security.policy=server.policy Server
java -Djava.security.policy=client.policy
-Djava.rmi.server.codebase=http://helios/~owner/
-Djava.rmi.server.hostname=helios Client localhost
Now,this works when both the server and client are on the same PC, but when I tried running it on a different PC on the same network, I got a
java.rmi.ConnectException: Connection refused to host: localhost; nested exception is:
java.net.ConnectException: Connection refused: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(Unknown Source)
at sun.rmi.server.UnicastRef.newCall(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at Client.main(Client.java:20)
Caused by: java.net.ConnectException: Connection refused: 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
sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(Unknown S
ource) at
sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(Unknown S
ource)
... 6 more
I am not very knowledgeable when it comes to networking. Can anyone explain why it's not working?
Your client is looking up the wrong Registry. It needs to lookup the Registry at the server host, not its own localhost.