定义在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 )我们想要获得在一个指定年出生的人的数据。
<?php /* 连接到数据库 */ mysql_connect("host","username","password"); mysql_select_db("PeopleData"); /* $_REQUEST['year']获得Android发送的年值,拼接一个SQL查询语句 */ $q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'"); while($e=mysql_fetch_assoc($q)) $output[]=$e; /* 转换以JSON格式输出 */ print(json_encode($output)); mysql_close(); ?>
String result = ""; /* 设定发送的年值 */ ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("year","1980")); /* 用HttpPost发送年值 */ try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");//上面php所在URL 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", "联网错误 "+e.toString()); } /* 转换响应字符串 */ try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);//注意"iso-8859-1"编码不支持中文。 /* 如需支持中文,设定MySQL为UTF8格式,在此也设置UTF8读取 */ 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", "转换响应字符串错误 "+e.toString()); } /* 解析JSON数据 */ 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", "解析JSON数据错误 "+e.toString()); }