使用PHP作为中间介来实现android链接远程数据库,这也是从网上搜集的两种简单的实现方法,差别不大,作为参考。

方法1

PHP代码:

conn.php是连接mysql数据库的。代码如下:

<?php
$dbhost = "localhost:3306";
$dbuser = "root"; //我的用户名
$dbpass = ""; //我的密码
$dbname = "testlogin"; //我的mysql库名
$cn = mysql_connect($dbhost,$dbuser,$dbpass) or die("connect error");
@mysql_select_db($dbname)or die("db error");
mysql_query("set names 'UTF-8'");
?>

login.php代码:

<?php
include ("conn.php");//连接数据库
$username=str_replace(" ","",$_POST['name']);//接收客户端发来的username;
$sql="select * from users where name='$username'";
$query=mysql_query($sql);
$rs = mysql_fetch_array($query);

if(is_array($rs)){
if($_POST['pwd']==$rs['password']){
echo "login succeed";
}else{
echo "error";
}
}
?>

class LoginHandler implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
//get username and password;
userName = user_name.getText().toString().trim();
password = pass_word.getText().toString().trim();
//连接到服务器的地址,我监听的是8080端口
String connectURL="http://192.168.1.100:8080/text0/com.light.text/login.php/";
//填入用户名密码和连接地址
boolean isLoginSucceed = gotoLogin(userName, password,connectURL);
//判断返回值是否为true,若是的话就跳到主页。
if(isLoginSucceed){
Intent intent = new Intent();
intent.setClass(getApplicationContext(), HomeActivity.class);
startActivity(intent);
proDialog.dismiss();
}else{
proDialog.dismiss();
// Toast.makeText(ClientActivity.this, "登入错误", Toast.LENGTH_LONG).show();
System.out.println("登入错误");
}
}
}

//登入的方法,传入用户 密码 和连接地址
private boolean gotoLogin(String userName, String password,String connectUrl) {
String result = null; //用来取得返回的String;
boolean isLoginSucceed = false;
//test
System.out.println("username:"+userName);
System.out.println("password:"+password);
//发送post请求
HttpPost httpRequest = new HttpPost(connectUrl);
//Post运作传送变数必须用NameValuePair[]阵列储存
List params = new ArrayList();
params.add(new BasicNameValuePair("name",userName));
params.add(new BasicNameValuePair("pwd",password));
try{
//发出HTTP请求
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//取得HTTP response
HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
//若状态码为200则请求成功,取到返回数据
if(httpResponse.getStatusLine().getStatusCode()==200){
//取出字符串
result=EntityUtils.toString(httpResponse.getEntity());
ystem.out.println("result= "+result);
}
}catch(Exception e){
e.printStackTrace();
}
//判断返回的数据是否为php中成功登入是输出的
if(result.equals("login succeed")){
isLoginSucceed = true;
}
return isLoginSucceed;
}
登入成功后会跳到主页:

***********************************************************************************************************************************************************

方法2:

<? php

mysql_connect("host","username","password");

mysql_select_db("PeopleData");

$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");while($e=mysql_fetch_assoc($q))

$output[]=$e;

print(json_encode($output));

mysql_close();

?>

android代码:

package lzu.ConnectMysql;

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import org.apache.http.NameValuePair;

import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

public class ConnectMysql extends Activity {

/** Called when the activity is first created. */

private TextView result;

private String content;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

result = (TextView)findViewById(R.id.content);

content = connecting();

result.setText(content);

//the year data to send

}

public String connecting(){

/*存放http请求得到的结果*/

String result = "";

String ss = null;

/*将要发送的数据封包 */

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("year","1980"));

InputStream is = null;

//http post

try{

/*创建一个HttpClient的一个对象*/

HttpClient httpclient = new DefaultHttpClient();

/*创建一个HttpPost的对象*/

HttpPost httppost = new HttpPost("http://202.201.0.245/test.php");

/*设置请求的数据*/

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

/*创建HttpResponse对象*/

HttpResponse response = httpclient.execute(httppost);

/*获取这次回应的消息实体*/

HttpEntity entity = response.getEntity();

/*创建一个指向对象实体的数据流*/

is = entity.getContent();

}catch(Exception e){

System.out.println("Connectiong Error");

}

//convert response to string

try{

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

StringBuilder sb = new StringBuilder();

String line = null;

while ((line = reader.readLine()) != null) {

sb.append(line + "/n");

}

is.close();

result=sb.toString();

System.out.println("get = " + result);

}catch(Exception e){

System.out.println("Error converting to String");

}

//parse json data

try{

/*从字符串result创建一个JSONArray对象*/

JSONArray jArray = new JSONArray(result);

for(int i=0;i<jArray.length();i++){

JSONObject json_data = jArray.getJSONObject(i);

System.out.println("Success");

System.out.println("result " + json_data.toString());

if( i == 0){

ss = json_data.toString();

}

else{

ss += json_data.toString();

}

}

}

catch(JSONException e){

System.out.println("Error parsing json");

}

return ss;

}

}

更多相关文章

  1. ObjectHttp使用介绍篇 —— 基础使用
  2. android mvp快速开发框架介绍(自动生成android代码工具介绍)
  3. Android(安卓)编程下图片的内存优化
  4. Android录音aac格式
  5. Android(安卓)6.0权限获取方式-shouldShowRequestPermissionRati
  6. android之动态新建txt文件与读取
  7. Android(安卓)Camera2架构-Frameworks下发预览和拍照请求流程Fra
  8. 阿里大牛又一波骚操作,安卓UI开发新技能-Jetpack Compose,绝了
  9. LayoutInflater

随机推荐

  1. Android App开发基础篇—四大组件之Activ
  2. android:绘图
  3. Android(安卓)NestedScrolling嵌套滚动的
  4. Android快速入门(一):Android介绍
  5. Android 源码解析-AsyncTask
  6. 初始Android
  7. Android网络收音机项目
  8. Android学习路线(八)为Action bar添加actio
  9. Android逆向之旅---解析编译之后的Androi
  10. 配置Android应用开发环境为什么需要安装