Here is a part from my program:
try {
Class.forName("com.mysql.jdbc.Driver");
InitializeData data = new InitializeData();
Connection con = null;
try {
Context ctx = data.getContext();
MysqlDataSource ds = (MysqlDataSource)ctx.lookup("database");
con = ds.getConnection();
...
where
public InitializeData() {
// configuring data source (data base)
ds = new MysqlDataSource();
ds.setUser("root");
ds.setPassword("%");
ds.setServerName("localhost");
ds.setPort(3306);
// configuring jndi
try {
Properties env = new Properties();
try {
env.load(new FileInputStream(env_props));
} catch (FileNotFoundException e) {
System.err.println("Unable to load jndi properties");
System.exit(1);
} catch (IOException e) {
System.err.println("IOException");
System.exit(1);
}
ctx = new InitialContext(env);
ctx.rebind("database", ds);
} catch (NamingException e) {
System.err.println("Naming Exception");
System.exit(1);
}
}
public Context getContext() {
return ctx;
}
As you can see, I try to connect to MySQL. Actually, MySQL is embedded in my java program.
When I connect via DriverManager (using con = DriverManager.getConnection("jdbc:mysql:mxj://localhost", "root", "");
) everything works. But using a DataSource object as it shown above invokes an exception:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection refused: connect
STACKTRACE:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at com.mysql.jdbc.jdbc2.optional.MysqlDataSource.getConnection(MysqlDataSource.java:425)
at com.mysql.jdbc.jdbc2.optional.MysqlDataSource.getConnection(MysqlDataSource.java:140)
at com.mysql.jdbc.jdbc2.optional.MysqlDataSource.getConnection(MysqlDataSource.java:110)
at statistics.DatabaseWorks.main(DatabaseWorks.java:26)
Could anybody, please, help me?
Some tests viewed that my program attempts to connect to a MySQL server, which is not embedded (see BalusC's answer). If I start the server(not embedded) everything works. So I need a way to say my program to start the local one. For some reason ds.setUrl("jdbc:mysql:mxj://");
doesn't work