Android如何串連MySQL資料庫

來源:互聯網
上載者:User

標籤:

Android開發中,大多數串連到遠程MySQL資料庫的方法是加入特定的Service到代碼中。由於MySQL通常是和PHP一起使用的,最簡單以及最常見的方法是寫PHP指令碼管理資料連線,以及從Android系統上使用HTTP協議運行這個指令碼


可以以JSON格式的方式編寫資料,Android和PHP之間,兩種語言都很容易嵌入JSON函數。


我示範的範例程式碼,根據給定的條件從資料庫讀取資料,在Android開發平台上建立日誌訊息接收資料。

假設我們有個命名為PeopleData的MySQL資料庫,並且使用以下的SQL語句建立了一個資料表:

 

[java] view plain copy 
  1. 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 
  1. ‘".$_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 
  1. 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資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.