[小代码]连接MySQL数据库(android,php,MySQL)

来源:互联网 发布:ubuntu vmdk文件下载 编辑:程序博客网 时间:2024/05/17 07:43
管理MySQL数据库最简单和最便利的方式是PHP脚本。
运行PHP脚本使用HTTP协议和android系统连接。
我们以JSON格式编码数据,因为Android和PHP都有现成的处理JSON函数。

下面示例代码,根据给定的条件从数据库读取数据,转换为JSON数据。
通过HTTP协议传给android,android解析JSON数据。

定义在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代码将是非常简单的:连接到数据库——运行一个SQL查询,根据设定WHERE语句块得到数据——转换以JSON格式输出    
例如我们会有这种功能getAllPeopleBornAfter.php文件:

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

Android部分只是稍微复杂一点:用HttpPost发送年值,获取数据——转换响应字符串——解析JSON数据。
最后使用它。
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());}

注意:android4.0以上联网代码只能放在子线程