Connect AVD with SQL Server Database Server throught JDBC - java

I'm currently trying to connect my app with a SQL Server database. There for I use JDBC.
Unfortunately I can't solve the following error message:
com.microsft.sqlserver.jdbc.SQLServerExceptiom: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error:"Sockets closed". ClientConnectionId: ...
I found already plenty of similar threads asking for a solution regarding this message. Some say I have to update JRE, some say I need a never Gradle and other say I should try JTDS. Anyway non of this helped me solving the issue.
But maybe I'm just stuck in my head and I'm overseeing something. Can anyone try to help me? And by the way where do you get your information, when you try to solve similar problems, because I don't think the documentation was helpful as well.
BTW. the SQL Server dos not have any SSL encryption and it uses Port 1433.
Setup:
JDBC: mssql-jdbc-9.4.1.jre16.jar
Gradle Version: 7.3.3
public class SqlHelper {
public static void main(Context mContext){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String url = "jdbc:sqlserver://192.168.190.8:1433;databaseName=Tablename;user=User;password=Password";
//String url = "jdbc:jtds:sqlserver://192.168.190.8:1433/DB_FrommEDV1;instance=SQLEXPRESS;";
Connection con;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url);
} catch (Exception e) {
System.out.println(e);
Toast.makeText(mContext, e.toString(),Toast.LENGTH_LONG).show();
}
}
}
I use the StrictMode because otherwise I get a NetworkOnMainThreadException.

Related

Receiving "No active connections found for master" while trying to connect Aurora read instance from java

I have already created a bug report(https://jira.mariadb.org/browse/CONJ-793) on MariaDB Jira but want to make sure it is a bug and there is nothing to do my side. I contacted the AWS support but they weren't very helpful.
We had problems with our lambda while connecting to the read database through read cluster URL.
I was able to isolate the problem in my local tunneling through the nat instance. I have no problems running the same code against the write instance. This is the Java test code I used.
private static final String connectionString
= "jdbc:mariadb:aurora://***.cluster-***.eu-west-1.rds.amazonaws.com:3306/db";
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
DriverManager.setLoginTimeout(10);
try (Connection conn = DriverManager.getConnection(connectionString, properties)) {
Statement statement = conn.createStatement();
try (ResultSet resultSet = statement.executeQuery("select * from exchange limit 1")) {
resultSet.next();
System.out.println(resultSet.getString(1));
}
} catch (SQLException exception) {
exception.printStackTrace();
}
}
And I am receiving this exception:
java.sql.SQLException: Communications link failure with primary. No active connection found for master.
at org.mariadb.jdbc.internal.failover.AbstractMastersListener.throwFailoverMessage(AbstractMastersListener.java:563)
at org.mariadb.jdbc.internal.failover.impl.MastersSlavesListener.checkInitialConnection(MastersSlavesListener.java:350)
at org.mariadb.jdbc.internal.failover.impl.MastersSlavesListener.initializeConnection(MastersSlavesListener.java:179)
at org.mariadb.jdbc.internal.failover.FailoverProxy.<init>(FailoverProxy.java:120)
at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:607)
at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:150)
at org.mariadb.jdbc.Driver.connect(Driver.java:89)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at com.company.ConnectionTestJava.main(ConnectionTestJava.java:19)
Have anyone faced this issue? It is hard to believe that I would be the only one facing this. Is it related to my setup or it is a bug? If it is a bug is there a workaround while waiting for a solution?
I ran into the same exception. Here is what worked for me.
So the issue here is with the protocol string, it needs to be changed from jdbc:mariadb:aurora to jdbc:mariadb and it works just fine.
I got this idea by looking at the mysql driver connection protocol and gave it a try and it worked!
Good luck!

Connect to mysql remote database using JDBC?

I'm a java beginner and I'm working on a simple application which connects to a remote mysql database using JDBC. I've tested it locally and it works just fine, however I cannot get it to work on for my remote server.
I don't think its of much use but heres the code:
Connection connection = null;
String dburl = "jdbc:mysql://314159265:3306/Db_Name";
String userName = "user";
String passWord = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dburl, userName, passWord);
Statement st = connection.createStatement();
String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
int rsI = st.executeUpdate(query);
System.out.println("Hi");
}catch (Exception e) {
System.out.println(e);
} finally {
if (connection != null) {
try {
connection.close();
System.out.println("Database connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
When I run this, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 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.
I'm pretty sure it must be some kind of server configuration issue.
Notes:
Username, password, IP, database name, etc. are just examples.
This could be a firewall problem, or a configuration problem. But I don't think it is a coding problem at all - you need to start troubleshooting the connection.
Trouble shoot by attempting to use third party client apps to connect to mysql. This will indicate whether it is configured for external access. Although it doesn't ensure that JDBC is visible from the outside, it does rule out some potential firewall problems.
Follow this guide to help you mess with your configurations
Remote MYSQL Database Access
If you are still stuck, it could be a coding problem so check out this page:
How to connent to a remote mysql database with java?
P.S. I am assuming you are using unix as the operating system.
I guess 314159265 could be replaced by some address....
like jdbc:mysql://localhost:3306/
or jdbc:mysql://127.0.0.1:3306/

Unable to get a SQL-Server connection

Im having difficulties trying to get a connection to my sqlserver database.
The database im using is SQL-Server 2008.
The driver im using is the one i got here: Microsoft download page
I use the following code:
public static final String URL_FORMAT = "jdbc:sqlserver://%s:%s;DatabaseName=%s";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
String connectionURL = String.format(URL_FORMAT, "10.31.3.3", 1433, "EPowerTest");
System.out.println("connecting to: "+connectionURL);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection(connectionURL, "sa", "*************");
if (connection == null) {
System.out.println("no connection was established");
} else {
System.out.println("succesfully connected");
}
}
Now this piece of code runs on my developers machine, im getting the following results:
connecting to: jdbc:sqlserver://...:1433;DatabaseName=******
succesfully connected
But when i run this piece of code on my developers machine it prints the follwing:
connecting to: jdbc:sqlserver://10.31.3.3:1433;DatabaseName=*******
and the second line never gets printed, because it seems DriverManager.getConnection does not return. This is not a firewall issue, since all three terminals (db server, developers machine and the test machine) are all on the same network. Why is my method not returning? am i missing some important SQLServer files?
Hope anyone here can help me with this annoying problem!
Check if the JVM in the machine that the connections hangs is the version 1.6.0_29. If it is, upgrade to a newer Java.
Here is another link explaining the issue.

JDBC Example for java

I have downloaded JDK 6 and also I have sqljdb4.jar and I have database.properties file that content the following data
database.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
database.url=jdbc:sqlserver://.;databaseName=UserInfo;integratedSecurity=true;
database.username=sa
database.password=admin
B.N : I'm installing the server on my machine and the server name = . , also I'm using Windows Authontication
My problem now is when I try to create connection I have the following error
com.microsoft.sqlserver.jdbc.SQLServerException:
The TCP/IP connection to the host
localhost, port 1433 has failed.
Error: Connection refused: connect.
Please verify the connection
properties and check that a SQL Server
instance is running on the host and
accepting TCP/IP connections at the
port, and that no firewall is blocking
TCP connections to the port. at
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:130)
I don't know what is the exact problem here
If any one can help I will be appreciated
Thanks in Advance
That's caused by many probabilities like
1- IP is worong
2- Port is wrong
3- There is firewall prevent machine to go out and connect to another IP
4- SQL server down .
try to use
public class JdbcSQLServerDriverUrlExample
{
public static void main(String[] args)
{
Connection connection = null;
try
{
// the sql server driver string
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// the sql server url
String url = "jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE";
// get the sql server database connection
connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
// now do whatever you want to do with the connection
// ...
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
}
}
What i need to explain is there is very good technology called " Persistence " is better than JDBC and is more than brilliant and easy to use .
The problem is that your SQL server is either
not installed,
not running or
not accepting TCP/IP connections.
Particularly the last one is nasty, as I remember that some versions of SQL Server have not configured the TCP/IP connector to run by default.
Well first and foremost we need to see your code. Second looking at the error message the database is A)not running
B) on a different port
or C) the code is incorrect.

How to connect MySQL to Java program

I ve installed MySQL (last update).
I need to code, that ll create & establish a connection with SQL DB
& manage the DB(using SELECT, INSERT, CREATE).
I did everything but, I am not able to create connection. I've also installed the MySQL/J connector, I just extracted the .zip pack in a folder & added the folder path in Variables).
Can anyone tell me wat is meant by URL in the below line?
Connection connection = DriverManager.getConnection(url, username, password);
I ve tried this:
String url = "jdbc:odbc:sqlserver://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
But it's not working. I am unable able to understand the term 'URL'.
Can anyone explain, the meaning of 'url' and wat should be done to connect to a SQL server from Java.
Update:
This is the Full code. It still cannot connect.
import java.sql.*;
public class TestDriver {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//This s wat actually i did for connection
System.out.println("Driver Loaded Succesfully");
}
catch (Exception e){
System.out.println("Unable to Load Driver!!!");
}
try {
Class.forName(com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
System.out.println("connection Established");
}
catch(Exception e) {
System.out.println("Couldnt get connection");
}
}
}
Can you tell me wat is the purpose of MySQL Connector/J?
In the question you seem to be using a MySQL jdbc driver with a SQL Server jdbc URL. This won't work.
If you are using a MySQL database:
Class.forName("com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
If you are using a SQL Server database you are going to need a completely different jdbc driver. jTDS is open source and a good option. Include the jtds.jar file in your classpath and use something like:
Class.forName("net.sourceforge.jtds.jdbc.Driver"); // initialise the driver
String url = "jdbc:jtds:sqlserver://localhost:1433/myfirstdb";
Here's an extract from your code:
} catch (Exception e) {
System.out.println("Couldnt get connection");
}
You should never suppress exceptions as long as you don't understand its cause. Replace it by at least:
} catch (Exception e) {
System.out.println("Could not get connection");
e.printStackTrace();
}
Or maybe
} catch (Exception e) {
throw new RuntimeException("Could not get connection", e);
}
Either way, you should see the exception type, message and trace. In your code snippet the possible exceptions are ClassNotFoundException and SQLException. The first one would mean that the driver is not properly placed in the classpath. The second one would mean that connection cannot be obtained. The exception message and/or trace should tell in detail about the underlying root cause of the problem.
You should always observe exceptions. They tell something about the cause of the problem. You know, once a cause is understood, the solution is nothing more than obvious :)
See also:
Short MySQL/JDBC tutorial - Contains explanation about exception causes.
Further,
Can anyone tell me wat is meant by URL in the below line?
An URL is an Uniform Resource Locator. It's a common way to locate (identify) unique resources in computer systems and networks. The URL syntax for the MySQL database is explained in the documentation of the JDBC driver.
Can you tell me wat is the purpose of MySQL Connector/J?
It's the JDBC driver. The JDBC API exist of almost only interfaces. The DB vendors should provide their own concrete JDBC API implementation, which is the JDBC driver. With a JDBC driver you'll be able to connect a specific database using JDBC API.
If its MS SQL Server,
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
For more info, see this to get started with Microsoft JDBC.
You can use any of the two JDBC drivers for MSSQL:
Microsoft SQL Server JDBC Driver
2.0
jTDS
For MS SQL Server driver 2.0, use
URL: jdbc:sqlserver://server:port; DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
For MySql & Java, see this on SO.
You forgot a " at Class.forName(com.mysql.jdbc.Driver");
It should be
Class.forName("com.mysql.jdbc.Driver");

Categories