I trying to do a JNDI lookup on a data source that lives in Weblogic 10.3.5.
I have the following code:
try {
//jbInit();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
env.put(javax.naming.Context.PROVIDER_URL,"t3://localhost:7001");
try {
Context ctx = new InitialContext(env);
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("jdbc/sandboxDS");
conn = ds.getConnection();
} catch(Exception e){
e.printStackTrace();
}
if(conn != null){
System.out.println("Got connection...");
String colDescQuery =
"select column1 from my_table where table_name = 'your_table' order by col_order_no";
Statement colDescStmt = conn.createStatement();
ResultSet colDescRS = colDescStmt.executeQuery(colDescQuery);
while (colDescRS.next()) {
System.out.println(colDescRS.getString(1));
}
} else {
System.out.println("No connection...");
}
} catch (Exception e) {
e.printStackTrace();
}
When I run this code as a stand alone Java program it works perfectly. The connection is found and the query returns the expected results.
When I use the same code in an applet and run it from the JDeveloper applet viewer it hangs where the InitialContext is instantiated. No exceptions are thrown, it simply hangs never to return.
Any ideas as to what is going on here? I have weblogic.jar and wlthint3client.jar in my classpath for both runs.
Thanks...
Applets have sandbox restrictions, so they cannot connect to the server other than where they were downloaded from.
Make sure your applet is also deployed to the same WebLogic Server that your JNDI data source is on.
Related
I have a simple database on my computer for testing purposed, and I'm trying to retrieve some information from the database, from my laptop. So I want my laptop to make a request to see the information inside my computers MySQL database. Below shows the java code I'm trying to run on my laptop to collect the first entry in the students table, which is located on my computer.
I have MySQL workbench installed on both my laptop and computer, is it necessary to be on both machines if the computer will store the data and the laptop only extracts data.
What I've learnt so far from researching is that the public ip should be used in the url instead of the ip for the computer, so I added that in but I received a CommunicationsException along with "Connection timed out" in the stack trace. I've read through this answer and this answer to a similar problem, but I'm having difficulty understanding both solutions, could someone refer me to a beginners guide to remotely accessing data from a database using MySQL.
public class TestRemote{
//JDBC variables
Connection connection;
Statement statement;
ResultSet resultSet;
//String variables
String url;
String user;
String password;
public static void main(String[] args) {
TestRemote sql = new TestRemote();
ArrayList<String> firstnames = sql.getColumn("students", "firstname", "studentid=4");
System.out.println(firstnames.get(0));
}
// Constructor
public TestRemote()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("couldnt find class");
}
url = "jdbc:mysql://81.159.3.167:3306/test"; //?autoReconnect=true&useSSL=false";
user = "user";
password = "pass123";
connection = null;
statement = null;
resultSet = null;
}
private void closeConnection(){
try{
if(connection != null)
connection.close();
if(statement != null)
statement.close();
if(resultSet != null)
resultSet.close();
connection=null; resultSet=null; statement=null;
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<String> getColumn(String table, String column, String where) {
ArrayList<String> resultsArray = new ArrayList<String>();
try {
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
if(!where.equals(""))
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table + " WHERE "+where);
else
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table);
while(resultSet.next()) {
String val = resultSet.getString(1);
if(val==null)
resultsArray.add("");
else
resultsArray.add(val);
}
//resultsArray = (ArrayList<String>) resultSet.getArray(column);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Model.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
closeConnection();
return resultsArray;
}
}
Your Java code is probably fine. But the question is, is on the other machine a MySQL server running and listening on port 3306 on the public IP? By default it should only listen on localhost, so you need to change your MySQL installation so that it listens to the public IP. Also make sure that no Firewall is blocking the access. Try connecting with the Workbench on the Laptop to reach the MySQL server on the other box. If you got this running, try your Java code again.
I have MySQL workbench installed on both my laptop and computer, is it
necessary to be on both machines if the computer will store the data
and the laptop only extracts data.
No what you call the "Computer" is your server here. it doesn't need mysql workbench. it only needs mysql server
the public ip should be used in the url instead of the ip for the
computer
A database should almost never be exposed on the public IP address. If you are having both computers on the LAN, the private network IP is what the server should listen on and that's what you should use on the connection string.
CommunicationsException along with "Connection timed out" in the stack
trace
Because the server is not running, not listening on that ip:port or firewalled to drop packets.
I connect to my Google Cloud SQL via my App Engine Java Rest API Project to retrieve and store data on my cloud. I can successfully communicate with the server via Localhost but after I publish, I get this error:
Trying to Run Query:
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.
While there's so many solutions out there, I'm sad to say none of them worked.
Here's my connection string:
String url = null;
try {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://APP_ENGINE_ID:SQL_INSTANCE_NAME/DB_NAME?user=root";
} else {
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://MY_IPV4_ADDRESS:3306/DB_NAME?user=root";
}
} catch (Exception e) {
e.printStackTrace();
}
I get this error via my Rest API after I publish it only. Basically, works via Localhost but not remotely on the cloud.
I debugged and pin pointed the place where it crashes. It happens after I try to establish a connection with the server and execute a query:
try {
//THIS is where it crashes
conn = DriverManager.getConnection(url);
try {
String query = "SELECT * FROM UserTable";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
//Code
}
st.close();
} finally {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
Has anyone faced this issue before?
Like Herman, Igor and Vadim pointed out, it was a simply error in my PROJECT_ID:INSTANCE_ID in this line:
Incorrect Code:
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://APP_ENGINE_ID:SQL_INSTANCE_NAME/DB_NAME?user=root";
}
I've been using my App engine ID instead of the Project ID, which I should have been using.
Corrected Code:
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://PROJECT_ID:SQL_INSTANCE_NAME/DB_NAME?user=root";
}
as You can see i have called using asyncTask in Android (same as Thread in java )
public class Connect extends AsyncTask<Context, Integer, Long>
{
protected Long doInBackground(Context... contexts) {
Connection connection;
String query = "Some query";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://<your cloud IP address>/<database schema you want to connect to>", "<user>", "<password>");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
hope you got it now :)
While the build paths are not correct I obtain “com.microsoft.sqlserver.jdbc.SQLServerDriver” from the stack trace. As they are built correctly, I obtain my printed statement “Successfully connected”. The JDBC is living within the getter/setters of the webservice as a method.
When I place the JDBC content in its own file with no builds and run as a java application I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
When I place the JDBC content in its own file with builds and run as a java application I receive: “Successfully connected”
When the method is called from a test file as a java application I receive: “Successfully connected”
Ex:
public static void main(String[] args) {
insert.main(args);
When the method is run as a java application on PO I receive: “Successfully connected”
When I place the method to be called under a setter (which will be invoked by the client, which will cause the jdbc to be invoked) I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Would you happen to have any tips for me? I’m clueless why it will work under being invoked as an application but not via client?
public class insert{
public static void main(String[] args) {
Connection con = null;
Statement st = null;
final String DB_URL = "jdbc:jtds:sqlserver://00.00.00.00:0000/DB";
// Database credentials
final String USER = "usrname";
final String PASS = "pw";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
st = con.createStatement();
System.out.println("successfully connected!");
} catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
finally {
try {
con.close();
} catch (Exception e) { /* ignored */ }
try {
st.close();
} catch (Exception e) {
/* ignored */
}
}
}
}
Any tips at this point would be greatly appreciated.
The problem is that your jar misses the necessary libraries that provides com.microsoft.sqlserver.jdbc.SQLServerDriver class and others to communicate with your SQL server. You have to make sure the library is loaded and available when is being executed from tomcat. Just copy your library and drop it inside %TOMCAT_INSTALL%/lib folder, where %TOMCAT_INSTALL% is the folder where your tomcat is installed, so the library will be available for every project (war, jar, etc) that runs in your tomcat installation.
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath
I've set the classpath envoirenment but still get an error "Exception:com.mysql.jdbc.Driver"
Do you have any idea what might be wrong?
Here is my test code:
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}
Exception:com.mysql.jdbc.Driver
Is most probably not the full error message. I guess it's a ClassNotFoundException and you simply do not have the MySQL JDBC driver as part of your classpath.
When running your program, you need to list the driver as well
java -cp .;mysql-connector-java-5.1.7-bin.jar JdbcExample1
(This assumes JdbcExample1.class and the .jar file are in the current directory)
I've set the classpath envoirenment
Setting the CLASSPATH environment variable is not necessary anymore (actually it never has been necessary). As a matter of fact it creates more problems than it solves.
Use the above syntax to supply the path to your driver and run your program
As horse says, I'm pretty sure it's a 'ClassNotFoundException'.
To be sure add "e.printStackTrace();" in your catch-block.
Always best to get a stack trace.