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!");
}
}
}
Related
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.
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();
}
}
Following is my Java code. In linux, it is working fine but in Windows I'm unable to insert data into the database on local disk. In NetBeans get it all right but .jar file not. JDBC driver see be good.
Connecting to database:
public static Connection connectToDb() {
try {
Connection connection = null;
DriverManager.registerDriver(new org.sqlite.JDBC());
//LINUX PATH
if (OSDetector.isLinux()) {
connection = DriverManager.getConnection("jdbc:sqlite:/home/" + userNameLinux + "/PDFMalwareDataAnalyser/DatabaseSQLite/database.db", NAME, PASSWORD);
//WINDOWS PATH
} else {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\PDFMalwareDataAnalyser\\DatabaseSQLite\\database.db", NAME, PASSWORD);
}
connection.setAutoCommit(true);
if (connection != null) {
System.out.println("Otvorená.");
}
return connection;
} catch (SQLException e) {
System.err.println(e.getClass().getName() + e.getMessage());
// System.exit(0);
}
return null;
}
Insertion:
public void insertDataToDatabase(int idReport) throws SQLException {
connection = new SQLiteJDBC().connectToDb();
PreparedStatement insertCommunication = connection.prepareStatement("insert into table_communication values(?,?);");
insertCommunication.setString(2, communicationsFinal.toString());
try {
insertCommunication.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
insertCommunication.close();
connection.close();
System.out.println("1. --- Insert do tabuľky TABLE_COMMUNICATION OK ---");
}
Try this:
connection = DriverManager.getConnection("jdbc:sqlite:C:/PDFMalwareDataAnalyser/DatabaseSQLite/database.db")
I wrote a java program which retrieve data from a PG gb, process them, and write them in an Oracle DB.
While the PG part is fully working, the Oracle one has issues.
I can connect to the DB, but every query ends with a rollback (ResultSet with Oracle is always null)
Of course i have both PG and Oracle JDBC driver.
Here are my DBs object and testing queries
private final static PostgresDB postgres = new PostgresDB("jdbc:postgresql://192.168.2.23:5432/T18CLEAN", "myPGUser", "myPGPasswd", true);
private final static OracleDB oracle = new OracleDB("jdbc:oracle:thin:#192.168.2.20:1521/EFFEVI.T18FV.IT", "myOracleUser", "myOraclePasswd");
private final static String testPostgres = "SELECT product_pricelist_item.x_product_name FROM public.product_pricelist_item;";
private final static String testOracle = "SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Then I setup the 2 connections:
PG:
public Connection getConnect() throws ClassNotFoundException {
System.out.println("-------- Posgres JDBC Connection Testing ------");
String url = c_url;
Connection conn = null;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", passwd);
props.setProperty("ssl", boolToString(sslEnabled));
try{
Class.forName("org.postgresql.Driver");
System.out.println("Postgres JDBC Driver Registered!");
} catch(ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(url, props);
System.out.println("You made it, take control your Postgres database now!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Failed to make connection to Postgres DB!");
}
return conn;
}
Oracle:
public Connection getConnect(){
Connection connection = null;
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return connection;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(c_url, user, passwd);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return connection;
}
if (connection != null) {
System.out.println("You made it, take control your Oracle database now!");
return connection;
} else {
System.out.println("Failed to make connection to Oracle DB!");
}
return connection;
}
After all these pass i perform queries
public ResultSet executeCommand(Connection c, String command) {
Statement st = null;
ResultSet rs = null;
try {
st = c.createStatement();
rs = st.executeQuery(command);
} catch (SQLException e) {
}
if(rs==null){
System.out.println("Failed to Execute command " + command);
} else {
System.out.println("Command Executed: " + command);
}
return rs;
}
Assuming that there are no parameters error... What could it be? Any help?
Thank you very much
Remove a semicolon at the end of the query.
Use this:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI";
instead of this one:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Also don't silently "swallow" an exception in your code:
} catch (SQLException e) {
}
Rethrow the exception, or at least print the error to the log:
} catch (SQLException e) {
log.error("Error while executing query " + command, e);
throw new RuntimeException("Error while executing query " + command, e);
}
I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.printStackTrace();
} finally {
//Finally Block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
//Nothing We Can Do
}
try {
if (conn != null)
conn.close();
} catch (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq