2

I know this question is asked before also, but I want to know whether we can Connect to external database (e.g mySQL) from android device without using a webservice.

  1. I have already build the app using webservice but now they have asked us to make it without using webservice.

  2. Can anybody knows or give any reference about same ?

  3. I have all the required data about the database location i.e. server name, db name etc.

Actually in my requirement I am downloading and xml using a webservice which will have all the details the connection string, database name, server name, username , password etc. but the connection is to be done on runtime.

4

1 に答える 1

1

はい、リモートデータベースに直接接続できます。ただ、セキュリティが不安です。

これを試して:

  1. MySQL JDBC をダウンロード

  2. Android プロジェクトに .jar ファイルを追加し、ライブラリとして追加します。

  3. AsyncTask を拡張したクラスを作成し、そこでメソッドを実行します。

public class connectToServer extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... args) {

        try {
            connect();
        } catch (Exception e) {
            Log.e("Error", e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String file_url)
    {

    }
}

public void connect(){
    Log.e("Android", "SQL Connection start");

    Connection conn = null;

    try
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        String ip = "[your host server]";
        String dbName = "[your dbName]";
        String user = "[your userName]";
        String password = "[your password]";

        String connString = "jdbc:mysql://" + ip + "/" + dbName +
        "";

        conn = DriverManager.getConnection(connString, user, password);

        Log.e("Connection", "Open");
        Statement statement = conn.createStatement();
        ResultSet set = statement.executeQuery("Select * from [table]");
        statement.setQueryTimeout(0);

        while(set.next())
        {
            Log.e("Data:", set.getString("[column_name]"));
        }
    }catch(Exception e)
    {
        Log.e("Error connection", e.toString());
    }

}//end method
于 2015-08-13T03:28:27.740 に答える