管理MySQL数据库最简单和最便利的方式是PHP脚本。
运行PHP脚本使用HTTP协议和android系统连接。
我们以JSON格式编码数据,因为Android和PHP都有现成的处理JSON函数。
下面示例代码,根据给定的条件从数据库读取数据,转换为JSON数据。
通过HTTP协议传给android,android解析JSON数据。
定义在MySQL有以下表,并有一些数据
images/loading.gif' data-original="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" />
1 CREATE TABLE `people` (2 `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,3 `name` VARCHAR( 100 ) NOT NULL ,4 `sex` BOOL NOT NULL DEFAULT '1',5 `birthyear` INT NOT NULL6 )
View Code
我们想要获得在一个指定年出生的人的数据。
PHP代码将是非常简单的:连接到数据库——运行一个SQL查询,根据设定WHERE语句块得到数据——转换以JSON格式输出
例如我们会有这种功能getAllPeopleBornAfter.php文件:
1 <?php 2 /* 连接到数据库 */ 3 mysql_connect("host","username","password"); 4 mysql_select_db("PeopleData"); 5 /* $_REQUEST['year']获得Android发送的年值,拼接一个SQL查询语句 */ 6 $q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'"); 7 while($e=mysql_fetch_assoc($q)) 8 $output[]=$e; 9 /* 转换以JSON格式输出 */10 print(json_encode($output));11 12 mysql_close();13 ?>
View Code
Android部分只是稍微复杂一点:用HttpPost发送年值,获取数据——转换响应字符串——解析JSON数据。
最后使用它。
1 String result = ""; 2 /* 设定发送的年值 */ 3 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 4 nameValuePairs.add(new BasicNameValuePair("year","1980")); 5 6 /* 用HttpPost发送年值 */ 7 try{ 8 HttpClient httpclient = new DefaultHttpClient(); 9 HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");//上面php所在URL10 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));11 HttpResponse response = httpclient.execute(httppost);12 HttpEntity entity = response.getEntity();13 InputStream is = entity.getContent();14 }catch(Exception e){15 Log.e("log_tag", "联网错误 "+e.toString());16 }17 /* 转换响应字符串 */18 try{19 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);//注意"iso-8859-1"编码不支持中文。20 /* 如需支持中文,设定MySQL为UTF8格式,在此也设置UTF8读取 */21 StringBuilder sb = new StringBuilder();22 String line = null;23 while ((line = reader.readLine()) != null) {24 sb.append(line + "\n");25 }26 is.close();27 28 result=sb.toString();29 }catch(Exception e){30 Log.e("log_tag", "转换响应字符串错误 "+e.toString());31 }32 33 /* 解析JSON数据 */34 try{35 JSONArray jArray = new JSONArray(result);36 for(int i=0;i<jArray.length();i++){37 JSONObject json_data = jArray.getJSONObject(i);38 Log.i("log_tag","id: "+json_data.getInt("id")+39 ", name: "+json_data.getString("name")+40 ", sex: "+json_data.getInt("sex")+41 ", birthyear: "+json_data.getInt("birthyear")42 );43 }44 }45 }catch(JSONException e){46 Log.e("log_tag", "解析JSON数据错误 "+e.toString());47 }
View Code
注意:android4.0以上联网代码只能放在子线程
原标题:【转】连接MySQL数据库(android,php,MySQL)
关键词:MYSQL