I am trying to connect my Android application to MSSQL server which is installed on my PC. I have previously been successful with connecting them but for some reason now I am getting a network error. I know that a direct connection shouldn't be made and a web service should be used but I am required to make a JDBC connection to the database.
The error I am getting is:
Network error IOException: failed to connect to /192.168.0.101 (port
1433) from /192.168.0.100 (port 37632)
I have configured my MSSQL Server to listen on port 1433.
This is the connection class.
package com.example.resourceapplication.LogIn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
public class ConnectionClass {
static String ip = "192.168.0.101";
static String classs = "net.sourceforge.jtds.jdbc.Driver";
static String db = "EKANBAN";
static String username = "root";
static String password = "root";
public static Connection CONN(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + username + ";password="
+ password + ";";
DriverManager.setLoginTimeout(2);
conn = DriverManager.getConnection(ConnURL);
Log.d("Hello","It Worked");
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
return null;
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
return null;
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
return null;
}
return conn;
}
}
This class had worked for me previously but for some reason doesn't work now. Any help would be appreciated.
Related
I have created a Public Class for my Database connection as am running various Database query's throughout the application
Every time i call the Class con always returns Null
But if i use it outside of the Class, and directly in the Activity then it connects and runs.
I have no idea why and would greatly appreciate any pointers in the right direction please.
Here are my ConnectionManager class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
static String serverName ="192.168.1.5";
static String serverPort ="1433";
static String databaseName ="DBNAME";
static String db = String.format("jdbc:jtds:sqlserver://%s:%s/%s", serverName, serverPort, databaseName);
static String un = "sa";
static String pass = "";
static Connection con;
public static Connection getConnection() {
try {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection(db, un, pass);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return con;
}
}
And from within my Activity i am calling it as follow:
try {
con = ConnectionManager.getConnection();
if (con == null) {
z = "Check Your Internet Access!";
Toast.makeText(StockEnquiry.this, z, Toast.LENGTH_LONG).show();
} else {
stmt = con.createStatement();
String query = "select * from Details where ID= '1111' ";
rs = stmt.executeQuery(query);
if (rs.next()) {
String sCode = rs.getString("Short_Code");
String sDesc = rs.getString("Short_Desc");
Toast.makeText(StockEnquiry.this, (sCode + " " + sDesc), Toast.LENGTH_LONG).show();
con.close();
} else {
Toast.makeText(StockEnquiry.this,"Invalid Code!", Toast.LENGTH_LONG).show();
}
Toast.makeText(StockEnquiry.this, "Message1", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
Toast.makeText(StockEnquiry.this, "Appears to have failed in catch", Toast.LENGTH_LONG).show();
}
}
}
So the message i was getting back was: android.os.NetworkOnMainThreadException'
After some digging i believe i am facing the issue because i am not running it as a asynchronous task.
Its possible to remove this restriction
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
So the connection class would look like the following.
import android.os.StrictMode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
static StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
static String serverName ="192.168.1.1";
static String serverPort ="1433";
static String databaseName ="DatabaseName";
static String db = String.format("jdbc:jtds:sqlserver://%s:%s/%s", serverName, serverPort, databaseName);
static String un = "Username";
static String pass = "Password";
static Connection con;
public static Connection getConnection() {
try {
try {
StrictMode.setThreadPolicy(policy);
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection(db, un, pass);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return con;
}
}
Calling the code from within the activity is untouched from the original post.
As a knock-on effect from this, You may get Application Crash / Lock-ups or slowness on poor network connection / coverage.
So its a bit of a sacrifice, but can be handled in other ways.
I am using android studio to develop an application and using Azure Sql Server to host my database. The problem is I was able to connect to my database on SQL server but it has an error of Object not found in my database.
I found out that it might be connecting to my master database instead of the database I want it to connect to. Is there any solution to solve the problem?
package com.example.lenovo.testing1;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
public class ConnectionClass {
String hostName = "haozailai.database.windows.net";
String dbName = "haozailai";
String user = "username";
String password = "password";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String ConnURL;
Connection conn = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://haozailai.database.windows.net:1433;database=haozailai;user=username;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
}catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return conn;
}
}
Picture of my database structure
I tried to connect my sqlserver via java jdbc and did not reproduce your issue.
I can connect to my application db successfully.
My test code:
import java.sql.*;
public class Test {
public static final String url = "jdbc:sqlserver://***.database.windows.net:1433;database=***;user=***password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
public static final String name = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static Connection conn = null;
public static PreparedStatement pst = null;
public static Statement stmt = null;
public static ResultSet rs = null;
public static void main(String[] args) {
try {
String SQL = "select * from dbo.Student";
Class.forName(name);
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close() {
try {
conn.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
After some research, I found out it is because of your connect url.
You need to modify your connect url :
jdbc:jtds:sqlserver://haozailai.database.windows.net:1433/<your application db name> ...
You could refer to the pages below for more details.
https://sourceforge.net/p/jtds/discussion/104389/thread/a672d758/
how to connect sql server using JTDS driver in Android
Update answer:
I have made a slight adjustment to your connect URL and can connect to my application database normally.
try {
String SQL = "select * from dbo.Student";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://***.database.windows.net:1433/<your database name>;user=***;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
Notice that remove the database=*** and add "/<your database name>" after your host string.
Please refer to the above code and try again.Any concern, please let me know.
Hope it helps you.
I know this answer is waay too late, but I found this video that totally works: https://www.youtube.com/watch?v=WJBs0zKGqH0
The thing is, you have to download a jtds jar, the guy in the video says where you can get it from and also, you need to add "jtds" before "sqlserver" in connection url and edit the way the 'databe' is written in the connection url, like this:
jdbc:jtds:sqlserver://serverName.database.windows.net:portNr:DatabaseName=dbName;user=....
I am having trouble establishing a connection between my app and an Oracle DB using JDBC drivers.
Host Oracle ver.: Oracle Database 11g Release 11.2.0.1.0 - 64bit Production
.Jar jdbc drivers I have tried: ojdbc5.jar, ojdbc6.jar, ojdbc14.jar, all from oracle itself.
I have granted the application the permission in the manifest.
<uses-permission android:name="android.permission.INTERNET" />
I get absolutely no response, nothing in the logcat. The SQL statement has no effect on the remote DB.
I can connect the remote DB with the same login credentials on my machine with SQL Plus and have all the privileges.
Code from MainActivity.java
package testapp.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.sql.ResultSet;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
super.onCreate(savedInstanceState);
ConnectOra db = new ConnectOra();
ResultSet rs = db.getResult();
ArrayList<String> list = new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString(1));
System.out.println(rs.getString(1));
}
} catch (Exception e) {
System.out.print(e);
}
}
public void btn(View view) {
startActivity(new Intent(MainActivity.this, MainActivity.class));//Just to refresh the mainact.
}
}
Code from ConnectOra.java:
package testapp.myapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.util.Log;
public class ConnectOra {
private Connection conn;
private Statement stmt;
public ConnectOra() throws ClassNotFoundException {
try {
System.out.println("in try");
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#103.A.B.C:15210/mdb";
this.conn = DriverManager.getConnection(url,"XXX","pw");
this.conn.setAutoCommit(false);
this.stmt = this.conn.createStatement();
} catch(SQLException e) {
Log.d("tag", e.getMessage());
}
}
public ResultSet getResult() throws SQLException {
ResultSet rset = stmt.executeQuery("select * from emp;");
System.out.println(rset+"");
stmt.close();
return rset;
}
}
The selected answer works and my code works too.
Android cant work with ojdbc5.jar, ojdbc6.jar as they require some Java SE components not available on Android. So, we have to use ojdbc14.jar since its older than ojdbc5.jar and ojdbc6.jar and doesn't require advance Java components, this also means that only the basic functions are there with ojdbc14.jar.
With ojdbc14.jar you might have to set "SQLNET.ALLOWED_LOGON_VERSION=8" in sqlnet.ora on the remote host running the DB. This will allow older clients to connect to newer DB otherwise it throws the error ORA-28040: No matching authentication protocol.
It is also vital to close the Connection and Statement after the SQL statements have been executed, else the changes aren't saved in the actual remote DB.
Can you try out this code and post the error log. Also a word of caution, you really shouldnt do this, you should have an application sever like this to manage connections to Oracle DB. But if you wanna play it unsafe, try out this code :
String driver = "oracle.jdbc.driver.OracleDriver"; //
String serverName = "localhost";
String portNumber = "1521";
String db = "XE";
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":"
+ db; // connectOracle is the data
// source name
String user = "system"; // username of oracle database
String pwd = "root"; // password of oracle database
Connection con = null;
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
Class.forName(driver);// for loading the jdbc driver
System.out.println("JDBC Driver loaded");
con = DriverManager.getConnection(url, user, pwd);// for
// establishing
// connection
// with database
Statement stmt = con.createStatement();
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
while (true) {
try {
socket = serverSocket.accept();
System.out.println("Connection Created");
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
// System.out.println("message: " +
// dataInputStream.readUTF());
ResultSet res=stmt.executeQuery("select * from person");
while(res.next()){
System.out.println(res.getString(1));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And read again, this is not recommended.
I have created a SQL server 2012 database. I need to connect to the database by using Java app created on another pc. this is my code but I cannot connect to the database, and I get error: "Login failed. The login is from an untrusted domain and cannot be used with Windows Authentication." (my code is working when both Java app and SQL server running on the same PC).
Appreciate your help.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String jdbcUrl = "jdbc:sqlserver://THINKPADPC:1433;databaseName=TestDB;integratedSecurity=true;";
conn = DriverManager.getConnection(jdbcUrl);
Have you tried sql server authentication. And pass username and password.
If you tryin windows authentication then it might be taking credentials from your(java) machine which has not been giving access on the hosted sql server machine.
Please Try this Connection and Change the ip, db , sa and password.
public class ConnectionClass {
String ip = "192.168.0.131";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "Andro";
String un = "sa";
String password = "Admnsql1~";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}`enter code here`
}
I am trying to establish a connection to MySQL database but when I attempt to connect I get the error:
SQLException: Access denied for user 'test'#'localhost' (using password: NO)
SQLState: 28000
VendorError: 1045
This is the Java program I am attempting to get the connection with and I am providing a password to the DriverManager.getConnection.
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.SQLException;
import java.sql.*;
//import com.mysql.jdbc.Driver;
public class jconnector_test{
public static void main (String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
//DriverManager.registerDriver (new Driver());
}
catch(Exception x)
{
System.out.println("Unable to load the driver class!" + x);
}
Connection conn = null;
String url = "jdbc:mysql://localhost/test";
String user = "test";
String password = "test";
try {
conn = DriverManager.getConnection(url, user, password);
//do something with the Connection
}
catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
}
SQLException: Access denied for user 'test'#'localhost' (using password: NO)
SQLState: 28000
VendorError: 1045