SQLException: Could not create connection to database server. SQLState: 08001 - java

I'm trying to connect my android studio to my AWS rds with JDBC.
public void GetText(){
TextView tx1 = findViewById(R.id.login_title);
ConnectionURL = "jdbc:mysql://awsrds-endpoint:3306/supplychain?user=admin&password=admin123";
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find the driver in the classpath!", e);
}
Connection conn = null;
Statement setupStatement = null;
Statement readStatement = null;
ResultSet resultSet = null;
String results = "";
int numresults = 0;
String statement = null;
try {
System.out.println("Connecting ...");
conn = DriverManager.getConnection(ConnectionURL);
System.out.println("Connected");
readStatement = conn.createStatement();
resultSet = readStatement.executeQuery("SELECT S_ID FROM STAFF;");
conn.close();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
and my error:
I/System.out: SQLException: Could not create connection to database server.
SQLState: 08001
VendorError: 0

The question here doesn't matter- do NOT connect to a db like this. In order to do this, you are putting your username and password in cleartext in your app. It is trivial to decompile the app and get it. This is unsafe. You should only ever access remote dbs via a webservice. That way your username and password do not need to leave your own devices.

Related

Unknown Host exception while connecting to Database using Selenium

When I am connected to the client network (using VPN) then i am successfully able to fetch the data from the database. But if I disconnect from the client network and run locally the same function then I am getting below error -
Connection Failed:SAP DBTech JDBC: Cannot connect to jdbc:sap://saphsg.XXXX.XX.com:30015 [Unknown host saphsg.XXXX.XXX.com:30015 [null], -709].
Below is the code which i am using -
public static void dbConnection(String query) throws ClassNotFoundException {
Connection connection = null;
try {
Class.forName("com.sap.db.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:sap://saphsg.XXXX.XXX.com:30015?encrypt=true&validateCertificate=false", UserID, Password);
} catch (SQLException e) {
System.err.println("Connection Failed:" +e.getMessage());
}
if (connection != null) {
try {
System.out.println("Connection to HANA successful!");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery(query);
while (resultSet.next()){
String Name1 = resultSet.getString(1);
String Name2 = resultSet.getString(4);
String Name3 = resultSet.getString(5);
System. out.println(Name1+"----"+Name2+"----"+Name3);
}
} catch (SQLException e) {
System.err.println("Query failed!");
}
}
}

Java program to connect azure database in Netbeans I'm getting error

I'm getting the following error:
I tried various ways I'm getting an error please see the following error.
run: java.lang.ClassNotFoundException:
com.microsoft.sqlserver.jdbc.SQLServerDriver at
java.net.URLClassLoader.findClass(URLClassLoader.java:381) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Class.java:264) at
com.sqldbsamples.App.main(App.java:23)
BUILD SUCCESSFUL (total time: 0 seconds)
This is my code: please help me with how to connect my database to azure using java program !!!
public class App {
public static void main(String[] args) {
// Connect to database
String hostName = "testchinnaa.database.windows.net:1433"; // update me
String dbName = "Test_Gopi"; // update me
String user = "chinna"; // update me
String password = "******"; // update me
String url = String.format("jdbc:sqlserver://testchinnaa.database.windows.net:1433;database=Test_Gopi;user=chinna#testchinna;password=*****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
Connection connection = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url);
String schema = connection.getSchema();
System.out.println("Successful connection - Schema: " + schema);
System.out.println("Query data example:");
System.out.println("=========================================");
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName "
+ "FROM [SalesLT].[ProductCategory] pc "
+ "JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectSql)) {
// Print results from select statement
System.out.println("Top 20 categories:");
while (resultSet.next())
{
System.out.println(resultSet.getString(1) + " "
+ resultSet.getString(2));
}
connection.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Sorry, you have to figure out if you are using MySql or MSSql. You said that you used mysql. However, in your connection string, it is a sqlserver which means it is a MSSql.
Here is the tutorial for accessing database using java:
You need to download connector for your database:
For MySql: MySQL
Connector/J
For MSSql: Microsoft JDBC Driver for SQL
Server
Manually add connector jar file to your classpath. Or you can use Maven dependencies manager to install and configure the Connector/J library in your project.
<!-- Example for mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
Code sample
For MSSql:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
connection = DriverManager.getConnection("conntection_string");
String SQL = "SELECT name FROM sysdatabases;";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SQL)) {
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
For MySql:
Connection conn = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connectionUrl = "jdbc:mysql://{server_name}.mysql.database.azure.com:3306?useSSL=true&requireSSL=false&serverTimezone=UTC";;
conn = DriverManager.getConnection(connectionUrl, "username_from_portal, like: jack#mysqldemo258", "password");
rs = conn.prepareStatement("show databases").executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
if(rs != null) rs.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

Getting org.postgresql.util.PSQLException: The connection attempt failed. error for connecting to Heroku

I am trying to connect a simple Java code with PostgreSQL database on Heroku. I have tried everything as needed, but I am getting the following error:
org.postgresql.util.PSQLException: The connection attempt failed.
I am not able to understand what is going wrong.
Following is the code I am using:
String dbUrl = "jdbc:postgresql://some-text.eu-west-1.compute.amazonaws.com:5432/some-text?ssl=true&sslmode=require";
String username = "some-text";
String password = "some-text";
try {
Class.forName("org.postgresql.Driver");
} catch (Exception e) {
System.out.println("Failed: " + e.toString() + e.getMessage());
}
try {
Connection connection = DriverManager.getConnection(dbUrl,username,password);
Statement statement = connection.createStatement();
String query = "select * from table";
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()){
System.out.println(resultSet.getString("column"));
}
} catch (SQLException e) {
System.out.println(e.toString());
}
I would appreciate if someone could help me with this.

Why do I get a java.sql.PreparedStatement that is closed from an opened connection to MySQL?

Why do I get a java.sql.PreparedStatement that is closed from an opened connection to MySQL?
This is my code:
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class MySqlTest1
{
Connection connection = null;
PreparedStatement stmt = null;
public MySqlTest1()
{
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
String url = "jdbc:mysql://localhost:3306/world?autoReconnect=true&useSSL=false";
String username = "jee";
String password = "????????";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password))
{
if (connection.isClosed())
{
System.out.println("Returned connection is closed");
return;
}
System.out.println("Database connected!");
System.out.println("create statement ...");
**stmt = connection.prepareStatement("select * from city");**
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
System.out.println("Selecting data ...");
ResultSet rs = null;
try {
System.out.println("execute query ...");
rs = stmt.executeQuery();
if (rs != null)
{
System.out.println("Data selected");
}
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
return;
}
The result from that code is
Loading driver...
Driver loaded!
Connecting database...
Database connected!
create statement ...
Selecting data ...
execute query ...
****SQLException: No operations allowed after statement closed.****
SQLState: S1009
VendorError: 0
I have tried with the Statement as well and looked into its values and and found that "isClosed" is true.
I have looked into the MySQL log but found nothing.
You are opening the connection in a try-with-resource block. Once the block is terminated, the connection is closed, and implicitly, all the statements created from it. Just extend this block to include the usage of the statement, and you should be OK.

Cannot connect Java to external mysql database

Hello i am currently building a programm that register users to mysql database. Everything works fine on localhost but when i try to connect to external database it gives me an error such as this below.
I have granted all privileges to the user in the database i am trying to acess and also i have the driver installed. Any ideas??
My code:
private void createEventListenerDBProperties() {
dbSubmitBtn.addActionListener((ActionEvent e) -> {
if (dbDriverChooser.getSelectedItem().equals("com.mysql.jdbc.Driver")) {
driver = (String) dbDriverChooser.getSelectedItem();
port = dbPortField.getText();
host = "jdbc:mysql://" + hostField.getText() + ":" + port + "/";
db = dbnameField.getText();
dbuser = dbUsernameField.getText();
dbpassword = new String(dbPasswordField.getPassword());
}
}
});
}
private Connection instanciateDB() {
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(host + db, dbuser, dbpassword);
System.out.println("Connection Established");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Connection not Established");
JOptionPane.showMessageDialog(Project2.this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
return con;
}
I think your way to connect is wrong. Instead of this:
con = DriverManager.getConnection(host + db, dbuser, dbpassword);
try this:
con = DriverManager.getConnection(host + db + "?user=" + dbuser + "&password=" +dbpassword);
Check this out, it may be useful.
http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html

Categories