Android開發中,大多數連接到遠程MySQL數據庫的方法是加入特定的Service到代碼中。由於MySQL通常是和PHP一起使用的,最簡單以及最常見的方法是寫PHP腳本管理數據連接,以及從Android系統上使用HTTP協議運行這個腳本。
可以以JSON格式的方式編寫數據,Android和PHP之間,兩種語言都很容易嵌入JSON函數。
我演示的示例代碼,根據給定的條件從數據庫讀取數據,在Android開發平台上創建日志消息接收數據。
假設我們有個命名為PeopleData的MySQL數據庫,並且使用以下的SQL語句創建了一個數據表:
- 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文件中有這個功能:
- '".$_REQUEST['year']."'");while($e=mysql_fetch_assoc($q)) $output[]=$e;print(json_encode($output));mysql_close();?>
Android部分比較復雜一些:
1. 使用HttpPost獲取數據,發送年份值
2. 響應的信息轉化成字符
3. 解析JSON數據,讀取你想要的數據。
- 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
- 踩