Android连接远程数据库(PHP+MYSQL)
Android虽然自带java.sql包,但是各数据库的JDBCDriver是否可用争议很多,不论国内网站还是国外网站,有人说能用,有人说不行,有人说虚拟机上能跑,上真手机就不行,有人说自己在手机上测试过也能跑。
但不管怎么说,直接连接远程数据库被公认不是一个很好的做法,至少在安全性上非常差的,所以现在最简单也是最流行的做法是访问远程服务器前段的PHP,PHP函数完成数据库操作,把结果经过JSON编码后传回,Android端再parse出结果。
SQL数据库创建测试表people代码如下:
CREATETABLE`people`(
`id`INTNOTNULLAUTO_INCREMENTPRIMARYKEY,
`name`VARCHAR(100)NOTNULL,
`sex`BOOLNOTNULLDEFAULT'1',
`birthyear`INTNOTNULL
)
PHP前端文件getAllPeopleBornAfter.php代码如下,查询出生年月在year之后的人:
<?php
mysql_connect("host","username","password");
mysql_select_db("PeopleData");
$q=mysql_query("SELECT*FROMpeopleWHEREbirthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
Android客户端的方法略微复杂一点,代码如下:
Stringresult="";
//首先使用NameValuePair封装将要查询的年数和关键字绑定
ArrayList<NameValuePair>nameValuePairs=newArrayList<NameValuePair>();
nameValuePairs.add(newBasicNameValuePair("year","1980"));
//使用HttpPost封装整个SQL语句
//使用HttpClient发送HttpPost对象
try{
HttpClienthttpclient=newDefaultHttpClient();
HttpPosthttppost=newHttpPost("http://localhost/getAllPeopleBornAfter.php");
httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));
HttpResponseresponse=httpclient.execute(httppost);
HttpEntityentity=response.getEntity();
InputStreamis=entity.getContent();
}catch(Exceptione){
Log.e("log_tag","Errorinhttpconnection"+e.toString());
}
//将HttpEntity转化为String
try{
BufferedReaderreader=newBufferedReader(newInputStreamReader(is,"iso-8859-1"),8);
StringBuildersb=newStringBuilder();
Stringline=null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
result=sb.toString();
}catch(Exceptione){
Log.e("log_tag","Errorconvertingresult"+e.toString());
}
//将String通过JSONArray解析成最终结果
try{
JSONArrayjArray=newJSONArray(result);
for(inti=0;i<jArray.length();i++){
JSONObjectjson_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(JSONExceptione){
Log.e("log_tag","Errorparsingdata"+e.toString());
}
更多相关文章
- Android查看apk文件的源代码(一)
- Android开发者必知的Java知识(三) 结合注解分析ActiveAndroid的
- 知乎 Android(安卓)客户端三方库敏感代码扫描机制 - FindDanger
- Android初学者的迷茫
- Android(安卓)layout 使用include和merge 标签
- Android(安卓)SQLiteException: near "": syntax error (code 1)
- 【Android:简单夜间模式切换实现】夜间模式切换,完整代码奉上!
- Android(安卓)五步修改状态栏颜色
- Android(安卓)application 中使用 provided aar 并没有那么简单