'How to connect sql server to android application?
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
connection();
}
});
}
public void connection(){
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
Connection conn=DriverManager.getConnection("jdbc:jtds:sqlserver://Asus-PC/PJH.V1;","","");
Log.w("Connection", "Error");
Statement stat=conn.createStatement();
ResultSet result=stat.executeQuery("SELECT * FROM Javher1");
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText(result.getString(1));
conn.close();
} catch (Exception e) {
// TODO: handle exception
Log.e("Error",e.getMessage());
Toast.makeText(getApplicationContext(), "Error"+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
I added a jtds1.2.7-jar file to the library.
The code runs I get the following error:
Error:Unknown server host name 'Asus-PC'.
If anyone knows anything please help me!
Thanks in advance.
Solution 1:[1]
Never, ever, ever connect directly to databases directly from app. Hackers can easily get hold of all your database, steal all your data and wipe the db clean...!
You should use a web service. Your app should only only only be communicating to the service, not to the database directly...
Don't blindly follow any tutorials that says so, its a very big security issue.
Solution 2:[2]
After 2 days of struggle.. finally i am able to connect my android app via MS SQL database..
Have a look it might help you too.
1
The very first thing that you have to do is to go to the link https://sourceforge.net/projects/jtds/ and download the drivers to connect the app through ms sql. Download jtds-1.3.1-dist.zip (551.2 kB) zip file and unzip it to find the jar folder inside it (jtds-1.3.1.jar).
2
Next step is to open your android studio and create a new project. (Blank activity).
Now open the Root Explorer(ALT+1)
From the tab displaying android at the top left, select the project module from the drop down list.
You can see the name of your project at the top. Right click this and add new directory. Paste the above jar file (unzipped from dist folder) to the folder.
Now add the jar file as a module in your project. Right click on the project directory and click on the option add module.
Browse the folder name where you have added the jar file( in above step) and allow the gradle to sync properly.
It's time to now add this lib to your android studio project as a dependency.
For this right click again on the project name tab and move to open module configurations (almost the last option).
It opens a window showing project. Move to the app dir (left hand side last tab) and click the + icon
ADD DEPENDENCY
(as a module)
Click it will show the module you just created. Now add this.
It will automatically compile and add the dependency in the gradle file.
3
You are almost done now.
Just copy the code as your main activity.
package com.example.administrator.testsqlserver;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import net.sourceforge.jtds.jdbc.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}}
public void Connect(View v)
{
EditText editText=(EditText)findViewById(R.id.editText);
String code = editText.getText().toString();
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
String connString = "jdbc:jtds:sqlserver://yourip :1433/your db;encrypt=fasle;user=username;password=password;";
String username = "your username";
String password = "your password";
conn = DriverManager.getConnection(connString,username,password);
Log.w("Connection","open");
Statement stmt = conn.createStatement();
Toast.makeText(MainActivity.this, "This works", Toast.LENGTH_SHORT).show();
ResultSet reset = stmt.executeQuery("SELECT NAME FROM tablename ;");
while(reset.next()){
String ans= reset.getString(1);
Toast.makeText(MainActivity.this,ans, Toast.LENGTH_SHORT).show();
}
conn.close();
} catch (Exception e)
{
Log.w("Error connection","" + e.getMessage());
e.printStackTrace();
}
}
}.
Solution 3:[3]
replace the computer name('Asus-PC') to ip-address
are you run in emulator try this 10.0.2.2
That's not efficient code please use web service to access the databse.
http://sochinda.wordpress.com/2011/05/27/connecting-to-net-web-service-from-android/
http://www.codeproject.com/Articles/304302/Calling-Asp-Net-Webservice-ASMX-From-an-Android-Ap
Solution 4:[4]
I've already done it this way but it's very inefficient. As the other comments have mentioned use a webservice instead, you shouldn't be saving your DB credentials on your device.
For this to work, you need to do two things, firstly,
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
You will also have to change the PC name you have entered to the LAN IP if you're on the same network or the the public IP address if you're connecting over the internet.
Also, if you're not on the same network as the server then you will also have to enable port forwarding on the router that is connected to your server.
WARNING: The port will always show as closed until you start a database engine on SQL Server with the name as the IP address of the computer which has the database.
Solution 5:[5]
the best way to connect your android application to a database is to build a rest api that can communicate with the data base and answer your requests . but if your like me and just testing out with android development you can read the article below to help you out https://medium.com/@nahomdesta61/connect-android-application-to-database-71975ce87b4a
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bhargavg |
| Solution 2 | Community |
| Solution 3 | |
| Solution 4 | Swaroop Ajit |
| Solution 5 |
