標籤:
管理MySQL資料庫最簡單和最便利的方式是PHP指令碼。
運行PHP指令碼使用HTTP協議和android系統串連。
我們以JSON格式編碼資料,因為Android和PHP都有現成的處理JSON函數。
下面範例程式碼,根據給定的條件從資料庫讀取資料,轉換為JSON資料。
通過HTTP協議傳給android,android解析JSON資料。
定義在MySQL有以下表,並有一些資料
1 CREATE TABLE `people` (2 `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,3 `name` VARCHAR( 100 ) NOT NULL ,4 `sex` BOOL NOT NULL DEFAULT ‘1‘,5 `birthyear` INT NOT NULL6 )
View Code
我們想要獲得在一個指定年出生的人的資料。
PHP代碼將是非常簡單的:串連到資料庫——運行一個SQL查詢,根據設定WHERE語句塊得到資料——轉換以JSON格式輸出
例如我們會有這種功能getAllPeopleBornAfter.php檔案:
1 <?php 2 /* 串連到資料庫 */ 3 mysql_connect("host","username","password"); 4 mysql_select_db("PeopleData"); 5 /* $_REQUEST[‘year‘]獲得Android發送的年值,拼接一個SQL查詢語句 */ 6 $q=mysql_query("SELECT * FROM people WHERE birthyear>‘".$_REQUEST[‘year‘]."‘"); 7 while($e=mysql_fetch_assoc($q)) 8 $output[]=$e; 9 /* 轉換以JSON格式輸出 */10 print(json_encode($output));11 12 mysql_close();13 ?>View Code
Android部分只是稍微複雜一點:用HttpPost發送年值,擷取資料——轉換響應字串——解析JSON資料。
最後使用它。
1 String result = ""; 2 /* 設定發送的年值 */ 3 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 4 nameValuePairs.add(new BasicNameValuePair("year","1980")); 5 6 /* 用HttpPost發送年值 */ 7 try{ 8 HttpClient httpclient = new DefaultHttpClient(); 9 HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");//上面php所在URL10 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));11 HttpResponse response = httpclient.execute(httppost);12 HttpEntity entity = response.getEntity();13 InputStream is = entity.getContent();14 }catch(Exception e){15 Log.e("log_tag", "連網錯誤 "+e.toString());16 }17 /* 轉換響應字串 */18 try{19 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);//注意"iso-8859-1"編碼不支援中文。20 /* 如需支援中文,設定MySQL為UTF8格式,在此也設定UTF8讀取 */21 StringBuilder sb = new StringBuilder();22 String line = null;23 while ((line = reader.readLine()) != null) {24 sb.append(line + "\n");25 }26 is.close();27 28 result=sb.toString();29 }catch(Exception e){30 Log.e("log_tag", "轉換響應字串錯誤 "+e.toString());31 }32 33 /* 解析JSON資料 */34 try{35 JSONArray jArray = new JSONArray(result);36 for(int i=0;i<jArray.length();i++){37 JSONObject json_data = jArray.getJSONObject(i);38 Log.i("log_tag","id: "+json_data.getInt("id")+39 ", name: "+json_data.getString("name")+40 ", sex: "+json_data.getInt("sex")+41 ", birthyear: "+json_data.getInt("birthyear")42 );43 }44 }45 }catch(JSONException e){46 Log.e("log_tag", "解析JSON資料錯誤 "+e.toString());47 }View Code
注意:android4.0以上連網代碼只能放在子線程
【轉】串連MySQL資料庫(android,php,MySQL)