MYSQL & Android 連接方式 - Android

By Sarah
at 2010-12-20T23:59
at 2010-12-20T23:59
Table of Contents
大家好~!
原po因為要做專題 研究了這部分好一陣子
google 還找不太到很完整的辦法 只能慢慢摸索
現在終於有小成果了 來跟大家分享一下連接方式
希望會幫助到需要的人:)
我只說明 比較重要的部分
========================================================================
***.java
String uriAPI = "http://(這裡填sever ip)/***(php檔名稱).php";
HttpPost httpRequest = new HttpPost(uriAPI); //我是用httppost
List <NameValuePair> params = new ArrayList <NameValuePair>();
params.add(new BasicNameValuePair("CatchNumber","2"));
//這行的參數會自動加在uriAPI後面 以此例子來說 會變成
http://(這裡填sever ip)/***(php檔名稱).php?CatchNumber=2
如果後面還需要其他參數 方法相同
而此處的2為字串 如果需要int 再php還要再轉過(後面說明)
try
{
httpRequest.setEntity(
new UrlEncodedFormEntity(params,HTTP.UTF_8));
這邊設成utf8 中文才不會亂碼 (但我還是亂碼目前還沒解決
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode()==200)
{
String strResult = EntityUtils.toString
(httpResponse.getEntity()); //資料庫抓過來後 我使用text列出
txv_Title.setText(strResult);
}
else
{
txv_Title.setText("Error
Response:"+httpResponse.getStatusLine().toString());
}
}
catch (ClientProtocolException e)
{
txv_Title.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (IOException e)
{
txv_Title.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (Exception e)
{
txv_Title.setText(e.getMessage().toString());
e.printStackTrace();
}
======================================================================
***.php
<?php
$link = mysql_connect("localhost","使用者名稱","密碼");
mysql_query("use (db名稱)");
$CatchNumber = $_POST["CatchNumber"]; //使用post接收java傳過來的CatchNumber
intval("CatchNumber"); //String 轉 Int
$result = mysql_query("select * from (表單) where No between '$CatchNumber'
and '3'",$link); //此PHP語法很基本 不懂自己翻
//我要註明的是 這邊把CatchNumber的值 也就是2 從java抓過來使用了
while ($row = mysql_fetch_row($result)){
for($i=1;$i<count($row);$i++){
echo $row[$i];
echo " ";
}
}
//上述為輸出方式 可依需要格式更改
mysql_free_result($result);
mysql_close($link);
?>
======================================================================
大概是這樣子
有什麼問題可以再詢問 (雖然我也不是很厲害XD
話說 我還沒研究出抓過來之後中文變亂碼的問題(其實是變一堆問號)
在資料庫看到是正常的
因為要重架SEVER 還沒空研究
有人可以幫忙解答嗎XDD
--
推 a1234957:WEB SERVICE XML-RPC 12/21 00:14
→ a1234957:JSON-PRC 12/21 00:14
樓上可以說清楚一點嗎.. 囧" 推 james79821:推一個~ 12/21 00:22
※ 編輯: nonebelieve 來自: 61.227.113.230 (12/21 00:23) 推 hrs113355:推 12/22 01:13
※ nonebelieve:轉錄至看板 AndroidDev 01/13 23:38 Tags:
Android
All Comments

By Damian
at 2010-12-22T16:57
at 2010-12-22T16:57

By Elvira
at 2010-12-23T13:25
at 2010-12-23T13:25

By Jack
at 2010-12-24T01:45
at 2010-12-24T01:45
Related Posts
聯絡人軟體自薦 "Group Contact"

By Sandy
at 2010-12-12T16:14
at 2010-12-12T16:14
[爆卦] Android 2.3 SDK公開了

By Quintina
at 2010-12-07T01:15
at 2010-12-07T01:15
Google Nexus S 官方網站

By Joe
at 2010-12-07T00:26
at 2010-12-07T00:26
推薦Android數十款不錯的遊戲

By George
at 2010-12-03T14:50
at 2010-12-03T14:50
去吧!繪圖人

By Thomas
at 2010-11-06T16:03
at 2010-11-06T16:03