问题
First of all. I am new to android application development environment and I am trying to connect to mssqlserver 2008 with simple android application using jtds-1.3.1.jar driver . I googled many example on internet but i failed to connect with database .
The exception i am getting is Network error IOException: connection time out
I don't know what is wrong with my code i am using Eclipse juno IDE.
here is my code
package com.example.Testproject1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.widget.TextView;
import java.sql.*;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectTodatabase();
}
public void connectTodatabase()
{
TextView txtView=(TextView)findViewById(R.id.textView2);
String url = "jdbc:jtds:sqlserver://XXX.XXX.X.XXX:1433;DatabaseName=VautomateuShoppi";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "VShopping_User";
String password = "VShopping_Pass";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{
// Establish the connection.
Class.forName(driver);
con = DriverManager.getConnection(url, userName, password);
// Create and execute an SQL statement that returns some data.
String SQL = "select * from SeoMaster";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
txtView.setText(rs.getString(2));
}
}
catch(Exception ex)
{
txtView.setText(ex.getMessage().toString());
}
}
}
回答1:
add these code
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
回答2:
Try This
public List<String> dbConnect(String Host, String Port, String db_userid,
String db_password) {
List<String> Db_list = new ArrayList<String>();
try {
String ConnectionString = "jdbc:jtds:sqlserver://" + Host + ":"
+ Port;
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(ConnectionString,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select name from sys.databases";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
Db_list.add(rs.getString(1));
}
} catch (Exception e) {
Db_list.add("Error");
e.printStackTrace();
}
return Db_list;
}
Refer Sql Database connect Using the JDBC Driver with android
来源:https://stackoverflow.com/questions/26052899/connecting-android-app-to-microsoft-sql-server-2008