android串連mysql資料庫

來源:互聯網
上載者:User

參考自:http://www.helloandroid.com/tutorials/connecting-mysql-database

 

使用PHP作為中間介來實現android連結遠端資料庫。

PHP代碼:

<?php

mysql_connect("host","username","password");

mysql_select_db("PeopleData");

  $q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))

        $output[]=$e; 

print(json_encode($output)); 

mysql_close();

?>

 

android代碼:

package lzu.ConnectMysql;

 

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

 

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

 

import org.apache.http.NameValuePair;

import org.apache.http.message.BasicNameValuePair;

 

 

import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

 

public class ConnectMysql extends Activity {

    /** Called when the activity is first created. */

private TextView result;

private String content;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

 

        result = (TextView)findViewById(R.id.content);

 

        content = connecting();

 

        result.setText(content);

      //the year data to send

    }

 

    public String connecting(){

    /*存放http請求得到的結果*/

    String result = "";

    String ss = null;

   

    /*將要發送的資料封包 */

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("year","1980"));

 

        InputStream is = null;

        //http post

        try{

        /*建立一個HttpClient的一個對象*/

                HttpClient httpclient = new DefaultHttpClient();

 

                /*建立一個HttpPost的對象*/

                HttpPost httppost = new HttpPost("http://202.201.0.245/test.php");

 

                /*佈建要求的資料*/

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

 

                /*建立HttpResponse對象*/

                HttpResponse response = httpclient.execute(httppost);

 

                /*擷取這次回應的訊息實體*/

                HttpEntity entity = response.getEntity();

 

                /*建立一個指向對象實體的資料流*/

                is = entity.getContent();

        }catch(Exception e){

               System.out.println("Connectiong Error");

        }

        //convert response to string

        try{

                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

                StringBuilder sb = new StringBuilder();

                String line = null;

                while ((line = reader.readLine()) != null) {

                        sb.append(line + "/n");

                }

                is.close();

 

                result=sb.toString();

                System.out.println("get = " + result);

        }catch(Exception e){

               System.out.println("Error converting to String");

        }

 

        //parse json data

        try{

        /*從字串result建立一個JSONArray對象*/

                JSONArray jArray = new JSONArray(result);

 

                for(int i=0;i<jArray.length();i++){

                        JSONObject json_data = jArray.getJSONObject(i);

                        System.out.println("Success");

                        System.out.println("result " + json_data.toString());

                        if( i == 0){

                        ss = json_data.toString();

                        }

                        else{

                        ss += json_data.toString();

                        }

                }

        }

        catch(JSONException e){

               System.out.println("Error parsing json");

        }

        return ss;

    } 

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.