How To Improve SQL Connection - java

Hello every body I'm working on application which is sends data from android app to MS-SQL server and main windows software in C#, which is receives data from MS-SQl server.
The problem is the programs takes too time to build a connection especially in android app some times it crash the app.
By the way the Internet speed some times goes week in our country.
I searched for a solution but not found in internet and I cannot figure out any way to solve it.
And I see the Viber, Watsapp, Massenger ... etc it sends data instantly or synchronously even if Internet speed is week.
So can I get some help and suggestion.
And there is a connection Helper method :
public Connection connections(){
IP="www.examlple.net";
DB="DB_test";
DBUserName="admin";
DBPassword="*****";
StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection=null;
String connectionURL=null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
connectionURL ="jdbc:jtds:sqlserver://"+IP+";DatabaseName="+DB+";integratedSecurity=true;user="+DBUserName+";password="+DBPassword;
connection = DriverManager.getConnection(connectionURL);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return connection;
}

For the sake of completeness, with JTDS you can set both a loginTimeout and a socketTimeout on a connection string. Refer to the remarks on these here.
But as others have said, you should go through a web API of some sort. Do you really want to expose your SQL server to the internet?
Also, I just noticed you have specified integrated security=true, and you have also specified a username and password. You can't do that. One is for windows auth (integrated security) and the other is for SQL auth (user and password). You would have to use a username and password. But don't. Don't do this. go through a web API.

Related

Connect AVD with SQL Server Database Server throught JDBC

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.

Java: Connecting to a MySQL Database? DriverManager.getConnection()? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
So I was just wondering, what (and probably, how much...) have I done wrong here with this code?
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
As I've triple-checked the username/password, I'm guessing it's something wrong with the host name. The database is only on the server (I don't have any kind of saved local version or anything...do I need to?).
And also, can someone just tell me if I'm on the right lines for what I want to do? Basically I've created a piece of software with a free version and a very cheap paid version. I was thinking that to prevent piracy, since the program requires internet connection anyway, I could store their email address as the username, then their computer's MAC address would be the password (each time the program was run, I would compare the MAC address on their PC with the one registered along with their email in the database. I've got no idea whether that is a good anti-piracy measure, but I was just wondering, if I manage to get the connection working, is that something that I'd be able to do or would there be e.g. security issues with that?
Anyway, thanks in advance :)
if it is not localhost i cannot comment on the host but you also have to give port number.It is missing.
Connection con = DriverManager
.getConnection("jdbc:mysql://"+pHost+":"+pPort+"/Your_mysql_schema_name",username, password);
and also in MYSQL your schema name would be your database name.Ensure that you are giving schema name and also port number.Usually for MYSQL its 3306
Writing a piece of java code to operate your database from a remote connection is not a good idea. Someone could reverse engineer your code and change your data.
You should atleast Implement an simple service on the net that could handle the spam you might receive, and protect your data.
I Think you missed the database port no in your URL .Try this :
try {
Class.forName("com.mysql.jdbc.Driver"); // Not Required for JDBC 4.0 onwards
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com: 3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Try instead of mysql1.000webhost.com to change with server IP address.
Example,
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://123.456.789.012:3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
I would recommend you some reading first. This slide show might present you how Java EE applications are build.
Next you might want to read a bit more how to connect your application with a database.
Hibernate is one of the most widely used tools for establishing connection between database and your Java program. It allows you to separate your connection data (e.g. username, password, connection url) from your code with use of configuration files in xml format. The line:
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
Is a very dangerous way of establishing connetion, as you are providing confidential credentials inside the code. There are ways to retreive this information from binary files.
You also asked, if is it worth having some local version of your database. The anwser is: Yes. Having your database locally might significantly speed up the time required for development and testing. It also allows you to work on your code even when no internet connection is available.
Providing authentication with use of MAC address is a very dangerous idea. Those addresses are attached to given machines. In other words the user will be able to connect to your application only with machine, on which he or she created an account. When using other computer (e.g. laptop at work) authentication will be denied.

Difficulty connecting to database using SQLserver jdbc

I'm trying to connect to my database using sqljdbc4, I'm pretty new to this so i followed a couple of tutorial but it still doesn't seem to work, When i try to run the program i get this Exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''. ClientConnectionId:f181fd37-7e28-4392-ac86-02914c2090e1
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
And this is my code:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
You are not passing any authentication credentials. If you want to use integrated security (windows authentication), then you need to explicitly specify that in your connection URL and you need to load the native library required for this.
See Connecting with Integrated Authentication On Windows on Windows on MSDN.
This essentially comes down to including the folder containing the (32 bit or 64 bit) sqljdbc_auth.dll in the java.library.path system property (see link for details) and adding integratedSecurity=true to your connection string:
DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=DBank;integratedSecurity=true");
You are passing empty username and password while connecting to the database in getConnection method:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
Try supplying the db username and password, for example:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","myusername","mypassword");

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/

NullPointerException in "DriverManager.getConnection" method

I have a problem establishing an connection to my MySql database via Java/Android. I have a database file (MyDatabase.db) on a Windows7 computer in my network. When I'm developing from another Windows7 computer (the file is accessible via the Windows Explorer and I can make changes to the database via SQLDatabaseExplorer) out of Eclipse the following Code works, but when installing my Application on my Galaxy Tab the "DriverManager.getConnection()" returns null.
try {
String url = "http://192.168.178.21/Users/test/userdata/Database/MyDatabase.db";
Class.forName ("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection (url);
System.out.println ("Database connection established");
} catch (SQLException e) {
Log.d("SQLException", "e.toString()");
}
The SQLException logged in LogCat is:
java.sql.SQLException: path to '//192.168.178.21/Users/test/userdata/Database/MyDatabase.db': '/192.168.178.21' does not exist
I guess my problem lies in the url String...? But I did not figure out how to change it, so that the connection can be established.
Thanks for any help,
Tim
EDIT:
Thanks for your help so far! I have written the question yesterday out of my mind, without looking onto my code... I'm sorry for that, because I have mixed up a lot of things... It is not a MySql-database but a sqlite-database... But I think that doesn't change a lot in coding. I'm using an jdbc sqlite driver. When starting the lines below in an Java-Eclipse Project everything works fine and the connection can be established. But on my Device I still got the Nullpointer...
Yesterday I have changed my code so that it should fit your advices. But the problem still resists... To be sure that it does not have to do with some rights or network settings I have copied the DB-File onto my Androiddevice and tried to connect to it directly with the following lines of code:
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = DriverManager.getConnection("jdbc:sqlite://mnt/sdcard/MyVideos34.db");
if (conn == null) {
Log.d("ConnectionError", "Connection is null");
return;
}
But also here getConnection throws a NullPointer and I don't know why... Did somebody have a assumption why the connection can be established out of Eclipse and fails on my Androiddevice? May I could have a wrong driver, that does not work from the device, but from Eclipse...?
Thanks in advance!
The url format for the MYSQL conenction string is
jdbc:mysql://[host][,failoverhost...][:port]/[database] »
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
If the host name is not specified, it defaults to 127.0.0.1. If the port is not specified, it defaults to 3306, the default port number for MySQL servers.
jdbc:mysql://[host:port],[host:port].../[database] »
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
Here is a sample connection URL:
jdbc:mysql://localhost:3306/sakila?profileSQL=true
please change accordingly
JDBC urls have the form : jdbc:mysql:/// but look at the duplicate code. You probably don't want to connect directly to a database from a mobile like this but will prefer a web service wrapper to do it.
try {
String url = "jdbc:mysql://localhost:3306/MyDatabase?user=root&password=root";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection (url);
System.out.println ("Database connection established");
} catch (SQLException e) {
System.out.println("SQLException" + e.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

Categories