通过php连接Android和Postgresql


connection between Android and Postgresql via php

我是android应用程序开发的新手。我已经给出了一个任务,开发一个可以通过PHP连接到PostgreSQL的android项目,该数据库不是本地主机。你们能帮我怎么连接吗。

SO中有各种关于PHP与Android应用程序集成的帖子。您想要搜索Android JSON。这就是我如何能够将我的应用程序链接到网络上的MySQL数据库。PostqreSQL应该没有什么不同,除了PHP查询调用。

你需要做的是编写一个PHP程序,连接到你的PSQL数据库并在上面运行查询。然后需要将查询格式化为JSON数组。下面的示例连接到一个mysql数据库。由于我从未使用过PostgreSQL,我不确定查询它的PHP代码是什么。不过,你应该可以在PHP.net上找到这些信息。

<?php
 $db = mysql_connect('localhost','mydatabase', 'mypassword');
 mysql_select_db("myDB");
 $TABLE = isset($_POST["table"]) ? $_POST["table"] : "rep_table";
 $q = mysql_query("SELECT * FROM " . $TABLE);
 while($row=mysql_fetch_assoc($q)) {
    $result[]=$row;
}
print(json_encode($result));
mysql_close();
?>

然后,你的应用程序会通过JSON接口调用这个PHP文件,然后你可以解析并获取值。

public class JSONHelper {
static ArrayList<NameValuePair> mArray = new ArrayList<NameValuePair>();
private static final String TAG = "JSONUpdater";
public String getJSONResult(String url) {
    String result = "";
    InputStream is = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        Log.d(TAG, "Client set");
        HttpPost httpPost = new HttpPost(url);
        Log.d(TAG, "Post set");
        if (!mArray.isEmpty()) {
            Log.d(TAG, "mArray is not empty!");
            httpPost.setEntity(new UrlEncodedFormEntity(mArray));
        } else {
            Log.d(TAG, "mArray is SO empty!!");
        }
        HttpResponse response = httpclient.execute(httpPost);
        Log.d(TAG, "response executed");
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch(Exception e) {
        Log.d("ScoreCard",e.toString());
    }
    //Retrieve the JSON data
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                Log.d(TAG, line);
            sb.append(line + "'n");
        }
        is.close();
        result=sb.toString();
    }catch(Exception e){
        Log.e("Scorecard", "Error converting result "+ e.toString());
        return result;
    }
    //Hopefully returning a string that can be converted to a JSON array...
    return result;
}
}

不要想让你的信息过载,因为它可能会让你不知所措。试着把它作为一个起点,看看你是否能到达你需要的地方。如果没有,请告诉我。如果可以的话,我会尽力帮你的。