Android鏈接遠程數據庫

計算機113 蔣鎮陽php

Android雖然自帶java.sql包,可是各數據庫的JDBC Driver是否可用爭議不少,不論國內網站仍是國外網站,有人說能用,有人說不行,有人說虛擬機上能跑,上真手機就不行,有人說本身在手機上測試過也能跑。前端

 

但無論怎麼說,直接鏈接遠程數據庫被公認不是一個很好的作法,至少在安全性上很是差的,因此如今最簡單也是最流行的作法是訪問遠程服務器前段的PHP,PHP函數完成數據庫操做,把結果通過JSON編碼後傳回,Android端再parse出結果。java

 

SQL數據庫建立測試表people 代碼以下:mysql

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
) sql

PHP前端文件getAllPeopleBornAfter.php代碼以下,查詢出生年月在year以後的人:數據庫

<?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();
?> json

Android客戶端的方法略微複雜一點,代碼以下:安全

String result = "";
//首先使用NameValuePair封裝將要查詢的年數和關鍵字綁定
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));

//使用HttpPost封裝整個SQL語句
//使用HttpClient發送HttpPost對象
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("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());
}
//將HttpEntity轉化爲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();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}

//將String經過JSONArray解析成最終結果
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
} 服務器

相關文章
相關標籤/搜索