how to embed oracle XE database in executable jar? - java

I have developed java application using java swings and oracle XE database in "myecplise". I have also created executable jar file and it runs fine in my pc but it is showing jdbc.odbc ClassNotFound exception and NullPointer Exception in other pc
my connection code is
import java.sql.*;
public class Connect {
static Connection con=null;
public static Connection ConnectDB(){
try{
// Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection("jdbc:oracle:thin:system/system#localhost");
return con;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
e.printStackTrace();
return null;
}
}
}

The DriverManager.getConnection("jdbc:oracle:thin:system/system#localhost") states that the driver manager will connect to the database located at your localhost. On the other PC it tries to locate the database on that other machine, since the database is not present there the exception will occur.
You have to change the connection to something like:
DriverManager.getConnection("jdbc:oracle:thin:#arg0:arg1:arg2", arg3, arg4);
Where
arg0: the IP of the machine that hosts the database.
arg1: The port that the database is listening to.
arg2: the SID of the database.
arg3: the schema username.
arg4: the schema password.

Related

How to connect to IntelliJ Ultimate's LocalHost MySQL database?

I went to Database > + > Data Source > MySQL
Here's what my panel looks like:
This is the error:
[08S01]
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.
java.net.ConnectException: Connection refused: connect.
and here's my connection file:
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection
{
private static Connection connection;
private static final String user = "root";
private static final String password = "root";
private static final String database = "jdbc:mysql://localhost:3306/user";
public static Connection getConnection()
{
if (connection == null)
{
try
{
connection = DriverManager.getConnection(database, user, password);
} catch (SQLException e)
{
e.printStackTrace();
System.out.println("Could not open database.");
System.exit(1);
}
}
return connection;
}
}
What could be my problem? I tried searching up for what others have tried but none of them seemed to work and I had to make several copies of my entire project because I kept messing things up trying those solutions to no avail. More specifically Solving a "communications link failure" with JDBC and MySQL
You need to have MySQL server installed and running to be able to connect to it from the other apps.
I suppose that your program did not run and so you went to configure some datasource in Intelij to make a connection with your Database.
If that is the case then
Your db is not reachable. Check if it is running and if all information provided here is correctly.
You don't need to set a InteliJ Datasource for your program to run. That is only for you to execute sql scripts using Intelij. It has nothing to do with some program that you develop using java which connects to that database.

MS SQL Connection: Android Studio never connects vs Eclipse IDE does

I am creating a program for a local organization to take inventory. App connects to SQL Server via MSSQL 8.2 connector. App on phone should allow for receiving and sending item information. I have a static class to connect to the database, that handles the connection. In Eclipse, I am able to successfully connect and query the database. In Android studio, I get errors on every attempt to connect.
-Server is hosted on same pc.
-Ports have been configured, repeatedly. Currently have inbound and outbound rules for TCP and UDP fully open. Dynamic ports are on for SQL server. Services for SQL server have been restarted dozens of times. 1433 has been enabled and toggled off, but are currently blank.
-Attempted to connect by IP address, host cannot be resolved
-Permissions edited to allow login access to modify the database
-Integrated security and TLS security tried at different times, both failed.
List of errors:
Connection to the host BLACK-G, "xxxxx" port 1433, has failed.
TCP/IP connection to the host failed, unable to resolve host.
Connection to the host named BLACK-G instance sqlexpress failed,No
address associated with hostname, open up UDP traffic to port 1434
Unknown host exception. Unable to resolve host BLACK-G
Connection Refused
Failed to connect
Connection to the host 192.168.1.219 has failed. Failed to connect to
192.168.1.219 (port 1433) from 192.168.1.87(port 33654) after 2478ms Verify connection properties.
Here is the code
package com.example.ccupboard_1;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseJAVA {
// #RequiresApi(api = Build.VERSION_CODES.KITKAT)//public static void main(String[] args) {
public static String Connect() {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://BLACK-G\\SQLEXPRESS;user=ay7;password=343434;databaseName=ayTestDatabase2;" ;
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT Fname, Lname from dbo.Customers";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
result += (resultSet.getString("Fname") + " " + resultSet.getString("Lname")+"\n");
}
} catch (SQLException e) {
e.printStackTrace();
result = e + "";
}
return result;
}
}
Snippet from main activity that calls connect method:
case R.id.buttonSignOut: { //used to test connection currently, simply attempts to connect and //returns the value to a textview on the page
Thread thread = new Thread() {
public void run() {
textviewLowItemAlert.setText(DatabaseJAVA.Connect());
}
};
thread.start();
break;
What would be the next step in resolving this issue? It works in Eclipse, but not in studio. I've tried more than a dozen different connection Strings, and most of them threw the same errors. Does my server not allow access to Android Studio? Most of the errors seem to be Android studio being incapable of locating it on the server.
Here's a snippet from a working app of mine where I can connect succesfully to a local ms sql.
In a config file I set the connection info.
public static String dbUser = "user";
public static String dbPassword = "password";
public final static String sqlString = "jdbc:jtds:sqlserver://ip:port//INSTANCENAME";
Then I start the connection like this.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
DriverManager.setLoginTimeout(5);
connection = DriverManager.getConnection(Config.sqlString, Config.dbUser, Config.dbPassword); // Connect to database
if (connection == null) {
ConnectionResult = "Verify Internet Connection";
Toast.makeText(activity, ConnectionResult, Toast.LENGTH_LONG).show();
Finally just do the query and close the connection.
Alright, was finally able to figure it out, with the JDBC-JTDS connector mentioned by JoaquinAlvarez.
Here's what happened:
-Used the connection info he provided, with my IP address, and a higher timeout
-Network Error IOException, EHOSTUNREACH(No route to host),
-Router changed my IP address, so had to fix that
-After that, I used my PCNAME\SQLEXPRESS for the the for the instance
-It returned Instance Unreachable, so I changed to SQLEXPRESS alone
-Then it returned DB Closed connection
-I looked at Windows Event Viewer, and it said:
"Encryption is required to connect to this server but the client library does not support encryption; the connection has been closed. Please upgrade your client library."
-I checked the SQL server in SQL SERVER Configuration Manager... Force Encryption was turned on.
-Tried again, and the JTDS connector finally connected to the Database and I was able to do things. No help with the MSSQL one yet though.
Thank you Mr. Alvarez!

How to connect to database which is hosted in remote machine using java program [duplicate]

This question already has answers here:
IO Error: The Network Adapter could not establish the connection
(12 answers)
Closed 3 years ago.
I'm trying to connect to a database which is hosted in a remote machine. I have a java project in my local and it has to connect to DB which is in remote machine for an update. What is the java code which I can use to connect. Traditional code of connection doesn't work and it shows below error.
import java.beans.Statement;
import java.sql.*;
public class connectTest {
public static void main(String[] args) {
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:#172.25.250.183:1521/aaadv4","boomerang","Telus2014");
Wrapper stmt=con.createStatement();
ResultSet rs=((java.sql.Statement) stmt).executeQuery("select * from ttv_dhcp_log.ACCT_MSG where SUB_IF='BACUPQXQOT01 PON 1/1/12/02:21.1.1'");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
I expect it to connect to DB but it fails with below message.
java.sql.SQLException: Io exception: The Network Adapter could not
establish the connection
There could be a couple of things you need to verify.
Check if the port is accessible from the machine . Use comamnds like telnet to check that.
Ex: telnet IPaddress portnumber
Check your firewall in your machine to see if connections to the port range are allowed or not.
Check the firewall rules in the machine where Oracle db is hoster as well.
Ensure your Credentials are correct.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection("jdbc:oracle:thin:#172.25.250.183:1521:aaadv4","username","password");
connection.close();
Use the above. Your DB connection URL contains a "/" instead of ":" . Also, ensure your IP address is accessible from your machine. If you are in the same network. It should be. If not, follow the debugging steps given above.

How can I connect to db2 database remotely

I am using following java application to connect db2 database for localhost and code is:
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50000/sample";
String user="admin";
String password="admin";
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url, user, password);
stmt = connection.createStatement();
}
catch (SQLException e) {
e.printStackTrace();
}
The problem is that when application and db2 is running on the same machine, then it is working, but if db2 database is on another machine then it is not working. I am using ip in my url which is:
String url="jdbc:db2://192.168.1.68:50000/sample";
And it's giving the following error:
com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException: [jcc][t4][2043][11550][3.59.81] Exception java.net.ConnectException: Error opening socket to server /192.168.1.64 on port 50,000 with message: Connection timed out: connect. ERRORCODE=-4499, SQLSTATE=08001
How can I connect to the database remotely?
Check if your private or public network firewall is on ?? If it is on then instead of doing it off make an inbound rule and then try to connect it with DB2 database from another system.

Connecting to local Mysql server from other pc

I have an local server which installed apache and mysql servers. both of them works very well. I can display the apache default page on browser fine. And I can manage the mysql database via terminal. All okey for now. But if I try to write code to use my DB. It gives me communication link error.
Here is the simple JAVA code:
public static void main(String[] args) {
String url = "jdbc:mysql://192.168.1.49:3306/test";
String username = "root";
String password = "1234";
System.out.println("Connecting database...");
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
AND HERE IS THE ERROR:
Connecting database...
Exception in thread "main" java.lang.IllegalStateException: Cannot
connect the database! at
servermysql.ServerMysql.main(ServerMysql.java:34) Caused by:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
THE SERVER İS UBUNTU 14.04 SERVER
THANK YOU FRİENDS
You have to set MYSQL bind-address to 0.0.0.0 because it usually only listens on 127.0.0.1 by default executing following command:
sed -i -e”s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/” /etc/mysql/my.cnf
Or manually change the bind-address to 0.0.0.0 in /etc/mysql/my.cnf and restart MYSQL.

Categories