標籤:
Android開發中,大多數串連到遠程MySQL資料庫的方法是加入特定的Service到代碼中。由於MySQL通常是和PHP一起使用的,最簡單以及最常見的方法是寫PHP指令碼管理資料連線,以及從Android系統上使用HTTP協議運行這個指令碼。
可以以JSON格式的方式編寫資料,Android和PHP之間,兩種語言都很容易嵌入JSON函數。
我示範的範例程式碼,根據給定的條件從資料庫讀取資料,在Android開發平台上建立日誌訊息接收資料。
假設我們有個命名為PeopleData的MySQL資料庫,並且使用以下的SQL語句建立了一個資料表:
[java] view plain copy
- CREATE TABLE `people` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`name` VARCHAR( 100 ) NOT NULL ,`sex` BOOL NOT NULL DEFAULT ‘1‘,`birthyear` INT NOT NULL)
想要讀取people資料表中出生日期在指定年份之後的的所有資料。PHP代碼是非常簡單的:
1. 串連到資料庫
2. 運行SQL查詢,其中有個塊依據於JSON格式的POST/GET值的資料。
比如,在getAllPeopleBornAfter.php檔案中有這個功能:
[java] view plain copy
- ‘".$_REQUEST[‘year‘]."‘");while($e=mysql_fetch_assoc($q)) $output[]=$e;print(json_encode($output));mysql_close();?>
Android部分比較複雜一些:
1. 使用HttpPost擷取資料,發送年份值
2. 響應的資訊轉化成字元
3. 解析JSON資料,讀取你想要的資料。
[java] view plain copy
- String result = "";//the year data to sendArrayList nameValuePairs = newArrayList();nameValuePairs.add(new BasicNameValuePair("year","1980"));//http posttry{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = newHttpPost("http://example.com/getAllPeopleBornAfter.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent();}catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString());}//convert response to stringtry{ 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();}catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString());}//parse json datatry{ JSONArray jArray = new JSONArray(result); for(int i=0;i
當然也可能使用HTTPS,發送密碼,訪問資料,或是在每一邊做更多複雜的資料處理,寫更多代碼。
-
頂
-
0
-
踩
Android如何串連MySQL資料庫