Java connect to OracleDB very slowly (with ojdbc6.jar and Linux) - java

I'm try to deploy the web services that have a connection to ORACLE database (10g).
Currently, I have
- CentOS 6.4 64bits
- Apache Tomcat 7.0.42 with JDK 1.7.0_25
- Ojdbc6.jar
When I calling web services with the same version of tomcat on Windows. It's working properly (0.1-0.5 Seconds/transaction).
but unfortunately, when I try to call it on CentOS server, It quite very slow (10-20 seconds/transaction)
The libraries are exactly same except the OS and as I monitoring catalina.out, there is no error but It's slowly when dbCreateConnection() was executed)
Please give me an advise.
Thanks :\
FYI, Here is the code in database section.
try {
Class.forName("oracle.jdbc.OracleDriver");
InputStream isr = this.getClass().getResourceAsStream("/"+"dbConfig.properties");
Properties prop = new Properties();
if (isr != null){
InputStreamReader isrProperties = new InputStreamReader(isr);
prop.load(isrProperties);
}
String dbURL = "jdbc:oracle:thin:#"+prop.getProperty("dbhost")+":"+prop.getProperty("dbport")+":"+prop.getProperty("dbname");
System.out.println("TRACE : getdbConfig --> "+dbURL);
String username = prop.getProperty("dbuser");
String password = prop.getProperty("dbpass");
dbConn = DriverManager.getConnection(dbURL, username, password);
if(dbConn != null){
System.out.println("TRACE : Connected to "+dbURL);
}
}
catch (SQLException ex) {
System.out.println("Error Message : getConnection Failed --> "+ex.getSQLState());
ex.printStackTrace();
}

Start Java with the JVM flag:
-Djava.security.egd=file:/dev/./urandom

Related

Moving a database in netbeans to another computer

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.

How do you define a stored procedure in java?

I've worked with web on asp.net C# defining connections with the following structure
try
{
sqlConnection = new SqlConnection(dbConnectionString);
SqlCommand command = new SqlCommand("sp_Test", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Id", SqlDbType.VarChar).Value = txtId.Text;
command.Parameters.Add("#Name", SqlDbType.DateTime).Value = txtName.Text;
sqlConnection.Open();
return command.ExecuteNonQuery();
sqlConnection.Close();
}
catch (SqlException ex)
{
Console.WriteLine("SQL MESSAGE Error" + ex.Message.ToString());
return 0;
}
...but I'm looking for its equivalent in java. The application I'm working on it is only local. I just need to connect my netbeans, the java IDE I'll use, to my ORACLE Database. The version of the database is Oracle 11g release 2. Thanks for the help!

How to connect to a Cloud Foundry MySQL database connection in Java?

create mysql as service on Cloud Foundry and tunnel to mysql database
this provides me connection string to mysql database i pass that information to my app.
it works from my machine but when i deployed that app on Cloud Foundry server then it gives an error in connection
this is my connection code, tell me what needs to change to be deployed on Cloud Foundry
public class DB {
private static Connection connection = null;
public static Connection getConnection() {
String url = "jdbc:mysql://127.0.0.1:10100/db8dad2d02e114ef6bc9d24e68367e33e";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,"uC0ag3NRJCT8c","p1nyZ38zadwfa");
System.out.println("Connect success fully");
return connection;
} catch (Exception e) {
System.out.println("Error");
System.out.println(e);
e.printStackTrace();
}
return null;
}
}
jayesh's answer is technically correct, but basically, the best way to deal with retrieving those information when inside a java app (assuming non-spring) is to use the cloudfoundry-runtime library: https://github.com/cloudfoundry/vcap-java/tree/master/cloudfoundry-runtime The README has examples of usage.
For completness, if using Spring, then things are even easier and chances are you don't even need to do anything special
Problem is here:
jdbc:mysql://127.0.0.1:10100
In this you're connecting to 127.0.0.1, it is a localhost, try giving the actual IP of your cloud server. Then it should work fine.
try {
String vcap_services = System.getenv("VCAP_SERVICES");
String hostname = "";
String dbname = "";
String user = "";
String password = "";
String port = "";
//for cloud config
if (vcap_services != null && vcap_services.length() > 0) {
JsonRootNode root = new JdomParser().parse(vcap_services);
JsonNode mysqlNode = root.getNode("mysql-5.1");
JsonNode credentials = mysqlNode.getNode(0).getNode(
"credentials");
dbname = credentials.getStringValue("name");
hostname = credentials.getStringValue("hostname");
user = credentials.getStringValue("user");
password = credentials.getStringValue("password");
port = credentials.getNumberValue("port");
String dbUrl = "jdbc:mysql://" + hostname + ":" + port + "/"
+ dbname;
System.out.println(dbUrl);
System.out.println(user + "password " + password);
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbUrl, user, password);
return connection;
} else {
//for local configuration
Class.forName("com.mysql.jdbc.Driver");
String url = jdbc:mysql://127.0.0.1:10100/db8dad2d02e114ef6bc9d24e68367e33e
connection = DriverManager.getConnection(url, "user name",
"password");
return connection;
}
} catch (Exception e) {
e.printStackTrace();
}
You're using information from vmc tunnel to try to connect. This is not going to work on the Cloud. You need to do what jayesh shows, and read the connection credentials from the Cloud Foundry environment instead. Eric's answer is even more complete :-)
I have the same problem. You must notice that "10100" is a port fortwarding to the mysql remote service.
you could use this just locally.Deploying your program locally with your database connection pointing to the forwarding port (101100).
But this won't work when you push your war to the Cloud Foundry Instance-
One solution is to use Spring based cloud beans. In my case i don't wan't to use this approach so i'm trying another solution...
I don't know if with the credentials (user, password, tc) created for the remote connection you could stablish a connection once you pushed your war to Cloud Foundry changing the forwarding port and using the default mysql port (3360)
In my case i don't want to use Spring Cloud Beans because the production application won't be deployed into a cloud storage.

Java program and mySQL connectivity issue: No suitable driver found

I've been having a problem with mySQL database connectivity. I'm getting an error:
No suitable driver found for jdbc:mysql://127.0.0.1/sakila.
I have installed mySQL workbench, and have the driver from here
http://dev.mysql.com/downloads/connector/j/
I have saved mysql-connector-java-5.1.18-bin and set the classpath to
C:\Program Files\Java\jre7\lib\mysql-connector-java-5.1.18-bin;
and started the mysql workbench where the database is found.
The code I am using is as follows: Which I am sure works, as I've asked a friend to test it form me. Unfortunately, we are developing on different platforms and could not instruct me as to how to fix this error. Has anyone an idea on how I can fix this?
public class Version {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://127.0.0.1/sakila";
//String url = "jdbc:mysql://localhost:3306/sakila";
String user = "root";
String password = "root";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("select * from actor;");
System.out.println("test");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
EDIT: Problem sovled. Did not have .jar appended to the end of the bin file, which is necessary.
You need to instantiate the driver before calling the getConnection :
String pdriver = "com.mysql.jdbc.Driver";
Class.forName(pdriver).newInstance();
Add the following
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
right before the line "con = DriverManager.getConnection(url, user, password);"
All you need to do is load the driver class before getting the connection from the drivermanager.
You need to place the connector jar file to your classpath or ...\jre1.6.0\lib\ext
Classpath is the one you should favor instead of the latter
You need to add the MySQL connecter library jar file to the classpath, rather than the directory where it is contained.
Are you not using an IDE like Netbeans or Eclipse? Setting up a command line development environment in Windows is not hard but it's not trivial either

i need the help for connecting mysql with java in ubuntu OS

I have my java application and try to connect with mysql database.But i can't able to get the output,i am getting the Exception error.I think i am not able to connect with the driver.My OS is Linux(Ubuntu).
nikki#nikki-laptop:~$ java -version
java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9) (6b20-1.9-0ubuntu1)
OpenJDK Client VM (build 17.0-b16, mixed mode, sharing)
nikki#nikki-laptop:~$ echo $JAVA_HOME
/usr/java/jdk1.6.0_20/bin/java
nikki#nikki-laptop:~$ echo $CLASSPATH
.:/usr/share/java/mysql.jar:/home/nikki/temp/src/jclass
My jdk path is /usr/lib/jvm/java-1.6.0-openjdk/jre
My Java program is
import java.sql.*;
class Query1
{
public static void main(String args[])throws Exception
{
try
{ // the mysql driver string
Class.forName("com.mysql.jdbc.Driver").newInstance ();
// the mysql url = "jdbc:mysql://THE_HOST/THE_DATABASE";
//String url = "sun.jdbc.odbc.JdbcOdbcDriver";
String url ="jdbc:mysql://localhost/mylib_db";
Connection conn = DriverManager.getConnection(url,"nikki","dkm007");
Statement stmt = conn.createStatement();
//ResultSet rs;
ResultSet rs = stmt.executeQuery("select title from Book_dim where cost=435.89");
while (rs.next())
{
String titlename = rs.getString("title");
System.out.println(titlename + "\n");
}
conn.close();
}
catch(Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
My output is
- - - - -
nikki#nikki-laptop:~/Documents/Chinu/mydbP$ javac Query1.java
nikki#nikki-laptop:~/Documents/Chinu/mydbP$ java Query1
Got an exception!
com.mysql.jdbc.Driver
I didn't added any driver...i don't know which Driver should i use .How can i add driver?
If possible plz send me the reply.
You need to add the Driver to the classpath of you application.
nikki#nikki-laptop:~/Documents/Chinu/mydbP$ java -cp /path/to/mysqldriver.jar Query1
You likely haven't included the mysql driver on the classpath. Download the JDBC driver from mysql and put the mysql-connector-java-[version]-bin.jar file on your classpath.
It would also be helpful to know more about just what exception is being thrown. Here is how you do that:
catch(Exception e)
{
e.printStackTrace();
}
Check these references out:
http://dev.mysql.com/doc/refman/5.1/en/connector-j-examples.html
http://dev.mysql.com/downloads/connector/j/
Download the mysql jdbc driver and add it to your classpath.

Categories

Resources