Connecting to PostgreSQL on Amazon EC2 through Java - java

I want to connect to PostgreSQL database in java, which is on Amazon EC2.
I can connect to it using a postgres client on Mac called Postico.
I specify next info:
Nickname
Host (ec2-xx-xx-xx-xx.xx-xx-x.compute.amazonaws.com)
User
Password
Database name
SSH host
User
Password - blank
Private key - .pem file
I could not find any example about how to connect it in Java.
I found some RedshiftJDBC driver and added it to project.
than I tried this:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
try {
this.connection = DriverManager.getConnection("jdbc:postgresql://" +DNS+"/"+myDBname, MYSQLUSER, MYSQLPW);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
I knew it would not work, but at least I tried))
I have no idea how to specify Private key in request (how to send it), or whatever.
Could someone help me ?
Thank you.

Try this the below code with PostgreSQL JDBC driver. You want to make the code a bit more resilient (e.g. check db for null in-between connecting and sending a query, etc.), but this should get you going.
private final String DB_HOST = "YOUR_EC2_HOSTNAME";
private final String DB_PORT = "5432";
private final String DB_USER = "YOUR_POSTGRES_USERNAME";
private final String DB_PASSWD = "YOUR_POSTGRES_PASSWORD";
private final String DB_NAME = "YOUR_POSTGRES_DBNAME";
private final String DB_URL = "jdbc:postgresql://" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME;
private final String INSERT = "INSERT INTO articles (date, name, uuid) VALUES (?, ?, ?)";
private Connection db = null;
public PostgreSQLService() {
try {
Class.forName("org.postgresql.Driver");
db = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWD);
} catch (ClassNotFoundException | SQLException ex) {
log.error(ex);
}
try (PreparedStatement st = db.prepareStatement(INSERT)) {
st.setEscapeProcessing(false);
st.setDate(1, new java.sql.Date(DateUtil.getToday().getTime()));
st.setString(2, "YOUR_NAME");
st.setObject(3, UUID.randomUUID());
if (st.executeUpdate() <= 0) {
throw new PostgreSQLServiceException("0 rows inserted while trying to insert a new row ::: " + st.toString());
}
} catch (SQLException sqle) {
throw new PostgreSQLServiceException("Received an SQLException trying to insert a row", sqle);
}
}
The Maven dependency is:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1208</version>
</dependency>
Note, you need to open up port 5432 in that EC2 instance's security group if you're executing this code from outside AWS.
I would also suggest looking at Amazon RDS. You can connect to it with the above code just the same as a Postgres instance running on EC2.
I hope this helps!

You don't specify that SSH info (SSH host, private key, etc.) when connecting from Java. The JDBC driver expects to be able to connect directly to the database server and does not support SSH tunneling. If you need to use SSH tunneling then you would have create that connection separately before starting the Java application.
If the Java application is running on AWS then you should be able to configure the network to allow a direct connection. If you are testing your Java application locally and need to connect to the remote database, then you run the ssh command locally to open a tunnel first. See this documentation: http://www.postgresql.org/docs/8.2/static/ssh-tunnels.html or this answer: PostgreSQL via SSH Tunnel

Related

SQL server connection refused when trying to connect to DB through a remote computer

I'm new to programming and I was making this chat server with login screen that extracts data from SQL server. It seemed fine when tested it in my laptop (which is where the database is). But when I tried to use to run the code on another desktop,
it kept saying:
"TCP/IP connection to host localhost, port 2175 has failed ..."
I have tried doing these so far:
enable TCP/IP protocols
set port to 1433
set dynamic port to 2175
run the SQL Browser (set "Local service" in Built-in Account section)
restart the SQL Server (set "Network service" in Built-in Account section)
create a bunch of TCP port rules (both Inbound and Outbound - Allow all)
create sqlserver program rules (both Inbound and Outbound - Allow all)
add sqlserver in firewall exception
Yet it doesn't seem to have any effect.
This is my code to connect to SQLserver:
public boolean connect(String SQL) {
String connectionUrl = "jdbc:sqlserver://localhost:2175;" +
"databaseName=TestConnection;integratedSecurity=True;";
Connection con = null;
Statement stm = null;
ResultSet rs = null;
boolean check = false;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
stm = con.createStatement();
if (SQL.contains("update") || SQL.contains("insert") || SQL.contains("delete") || SQL.contains("UPDATE") || SQL.contains("INSERT") || SQL.contains("DELETE")) {
int clu = stm.executeUpdate(SQL);
if (clu == 0)
check = false;
else
check = true;
}
else {
rs = stm.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString(1) + " | " + rs.getString(2));
check = true;
}
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stm != null) try { stm.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
return check;
}
I'm using SQL server 2016. I know there're tons of topics discussing about this problem but I can't seem to find the solution.
I also need to mention: the desktop I'm trying to run my code on doesn't have SQL server installed. Does it need to?
String connectionUrl = "jdbc:sqlserver://localhost:2175;" +
"databaseName=TestConnection;integratedSecurity=True;";
Above code means, you are trying to connect to database, which is installed on same machine (i.e. localhost).
Now, if you are trying to connect to remote server, then you need to use its IP address instead. Also, you need to make sure they are in same network (try pinging that machine using its IP adddress).

Unable to connect to Azure using JDBC (based upon the connection string and samples provide) due to SSL issue

Am getting the following error: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Connection reset by peer: socket write error."
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://XXXXX.database.windows.net:1433;"
+ "database=VDB;"
+ "user=XXX#VVV;"
+ "password=XXXX;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 2 * from Application";
statement = connection.createStatement();
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " "
+ resultSet.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the connections after the data has been handled.
if (resultSet != null) try {
resultSet.close();
} catch (Exception e) {
}
if (statement != null) try {
statement.close();
} catch (Exception e) {
}
if (connection != null) try {
connection.close();
} catch (Exception e) {
}
}
}
}
I'm only trying to do the "sample" connection snippet of code as referenced on the Azure site (which points to a MS entry), modified only to match my db and test table but without success.
Having reviewed all there is to know, I have:-
ensured that I'm using the right sqljdbc (I've tried all 4)
have the sqlauth.dll on the CLASSPATH
have set the sample up EXACTLY as shown; and incorporated the string that Azure offers.
I have tried various combinations of encrypt and trust without success. As I'm a newbie to Java and Azure, I'm reluctant and unsure how to fiddle with the JVM security settings.
I've proven that my machine can talk to the Azure database (through a VB ODBC connection); and I've tested with the firewall down.
Any thoughts?
I tried to reproduce the issue, but failed that I could access my SQL Azure Instance using the code which be similar with yours.
The difference between our codes is only as below, besides using the connection string of my sql azure instance.
Using the driver sqljdbc4.jar from the sqljdbc_4.0 link.
Using the code Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); to load MS SQL JDBC driver.
Not adding the sqlauth.dll file into the CLASSPATH.
Check my client IP which has been allowed by SQL Azure IP firewall.
Using the sql select 1+1 to test my code, and get the value 4 from code result.getInt(1).
That's fine for me. If you can supply more detals for us, I think it's very helpful for analysising the issue.
Hope it helps.

Connecting to MySql Database using Java

So I've been teaching myselft mysql and am trying to integrate it into my Java code. I've looked at some past code snippets and tutorials and I can't seem to figure out why my code is incorrect. (removed password for obvious reasons)
Here's what I'm using to connect
public static void connectionToMySql(){
String host = "mysql9.000webhost.com";
String username = "a9808220_pin";
String pass = "";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(host,username,pass);
/*insert code*/
connection.close();
System.out.println("It worked :)");
} catch (Exception e) {
System.out.println("Something went wrong :(");
e.printStackTrace();
}
}
I get an exception that there's no suitable driver. I'm not sure why because I have the jar downloaded and pathed correctly
Your connection should be a JDBC URL in the form
String url = "jdbc:mysql://mysql9.000webhost.com:3306/";
Now in order for this to work you should:
1) Verify that mySQL is running on the host mysql9.000webhost.com
2) Verify that the port is the default port ie 3306, if not change the code above to use the right port
String host should be like
String host = "jdbc:mysql:ip:port"//ip or hostname
example code that works for me...
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:1433;"
+"databaseName=test;"
+"user=sa;"
+"password=xxxxx;");
System.out.println("connected");

connecting with Derby from within the java application

this program works fine when i connect the java db under the 'Services' tab in netbeans but when i try to open the executable jar file of the prog outside neatbeans it doesn't work at all. I want this java application to be accessible by multiple users as i wish to put it on the my local network so i figured that i need to connect to the Derby database in network mode....am i correct.?.....how should i fix this..?following is code snipet of my application
public void DoConnect() {
try {
/*
** Load the Derby driver.
** When the embedded Driver is used this action start the Derby engine.
** Catch an error and suggest a CLASSPATH problem
*/
Class.forName("org.apache.derby.jdbc.ClientDriver");
try {NetworkServerControl server = new NetworkServerControl();
server.start (null);}
catch(Exception e)
{
System.err.println(e.getMessage());
}
System.out.println(driver + " loaded. ");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
System.out.println("\n >>> Please check your CLASSPATH variable <<<\n");
}
try {
//CONNECT TO THE DATABASE
String host = "jdbc:derby://localhost:1527/Employee";
String uName = "admin";
String uPass = "admin";
//EXECUTE SQL QUERY AND LOAD RESULTSET
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM Workers";
rs = stmt.executeQuery(SQL);
//MOVE CURSOR TO FIRST RECORD AND GET DATA
rs.next();
int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first_name = rs.getString("First_Name");
String last_name = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
//DISPLAY THE FISRT RECORD IN THE TEXT FIELD
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
IMHO it is bad practice to use a Derby database in network mode and to start the server in the same application. You combine all weaknesses of both world :
you cannot access the database from the outside (you server has to be local)
what happens if you server is allready running (if multiple executions on same node) ?
I think it works fine under Netbeans, because Netbeans is doing all the housekeeping for you : starting the server when you access to it via Netbeans interface, and closing it when closing Netbeans.
I think you should try the folowing :
start a server (manually) from outside of your application
remove the code for launching server from your app
(and do not forget to stop server when you have finished with it ...)
By the way I cannot understand what you mean by "not even starting" : if you start it from command line, you should have at least an error message ...
The way you've written the program there is no reason to meddle with the services tab. You should be able to just run (debug) the program directly in NB. Set a breakpoint, debug and step through it. When that works you can try to run from the command line.

Android connection failure with MySQL Database

I am trying to connect to my MySQL database in a new project that I am working on. The error message that I receive is: CommunicationsExceptions: Communications link failure.
I have tried to connect to my friends database, and it is working correct, but as soon as I try with my own localhost server I get errors.
I have also tried to write the exact same code in a JAVAFX application in netbeans and it is working perfectly, it is like there is something wrong with android and localhosts..
Here is my code:
private Connection conn = null;
private String dbName = "world";
private String user = "root";
private String pwd = "root";
private Statement statement = null;
public void connectingDatabase() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Found instance");
} catch (Exception ex) {
System.out.println("No instance ");
}
try {
setConn(DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/" + getDbName() + "?user=" + getUser() + "&password=" + getPwd()));
System.out.println("Connecta till " + getDbName());
} catch (Exception ex) {
System.out.println("no connection");
System.out.println(ex);
}
}
If I use my friends IP instead of 127.0.0.1:3306 or localhost it is working.
Does someone have any expertise in this kinds of problems?
Since the code is running on Android device and you want to connect to the MYSQL server running on your desktop, you cannot use 127.0.0.1 for connecting to the database. Instead use the ip address of the machine where MySQL database is hosted.
If localhost or 127.0.0.1 is still not working. Assign a static IP on your computer/server i.e: 192.168.1.10 and then use that in your connection URL
Good luck.

Categories

Resources