计算机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());
} 服务器