开发工具:WampServer 里面集成了php ,mysql。
最近在学习,android跟电脑的数据库连接,然后从网上的大神学习了一下,接着弄了两天最后才搞定了。
代码请移步到:http://download.csdn.net/detail/linqg24/8609587
在wampservel 下的www目录下放两个php文件,有conn.php和test.php
conn.php
<?php
$con=mysql_connect("localhost:3306","root","123456") or die("访问数据库失败".mysql_error());
mysql_select_db("test2",$con) or die("连接数据库失败".mysql_error());
mysql_query("set names 'gbk'");
?>
test.php
<?php
// array for JSON response
$response = array();
include("conn.php");
// check for required fields
if (isset($_POST['name']) && isset($_POST['password']) ) {
$name = $_POST['name'];
$password = $_POST['password'];
// $name ="张三";
//$password="123456";
$result = mysql_query("INSERT INTO test(name,password) VALUES('$name', '$password')");
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing ";
// echoing JSON response
echo json_encode($response);
}
?>
在客户android端
有三个activity 分别是DialogUtil.java、JSONParser.java、MainActivity.java
MainActivity.java代码如下:
package com.example.mysql_test;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import com.android.net.DialogUtil;
import com.example.mysql_test.JSONParser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText name;
EditText password;
Button login_button;
private static String url = "http://192.168.1.102:80/test.php";
//private static String url = "http://10.0.2.2/test.php";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.name);
password=(EditText)findViewById(R.id.password);
login_button=(Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(validate()){
new Up().execute();
}
}
});
}
private boolean validate()
{
String name1 = name.getText().toString().trim();
if (name1.equals(""))
{
DialogUtil.showDialog(this, "您还没有填写建议", false);
return false;
}
String password1 = password.getText().toString().trim();
if (password1.equals(""))
{
DialogUtil.showDialog(this, "您还没有填写建议", false);
return false;
}
return true;
}
class Up extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("正在上传..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String name1 = name.getText().toString();
String password1 = password.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name1));
params.add(new BasicNameValuePair("password", password1));
try{
JSONObject json = jsonParser.makeHttpRequest(url,
"POST", params);
String message = json.getString(TAG_MESSAGE);
return message;
}catch(Exception e){
e.printStackTrace();
return "";
}
}
protected void onPostExecute(String message) {
pDialog.dismiss();
//message 为接收doInbackground的返回值
Toast.makeText(getApplicationContext(), message, 8000).show();
}
}
public static final String removeBOM(String data) {
if (TextUtils.isEmpty(data)) {
return data;
}
if (data.startsWith("\ufeff")) {
return data.substring(1);
} else {
return data;
}
}
}
JSONParser.java代码如下:
package com.example.mysql_test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
Log.d("json", json.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
DialogUtil.java代码如下:
package com.android.net;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.View;
import android.app.Activity;
public class DialogUtil
{
// 定义一个显示消息的对话框
public static void showDialog(final Context ctx
, String msg , boolean closeSelf)
{
// 创建一个AlertDialog.Builder对象
AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
.setMessage(msg).setCancelable(false);
if(closeSelf)
{
builder.setPositiveButton("确定", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// 结束当前Activity
((Activity)ctx).finish();
}
});
}
else
{
builder.setPositiveButton("确定", null);
}
builder.create().show();
}
// 定义一个显示指定组件的对话框
public static void showDialog(Context ctx , View view)
{
AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
.setView(view).setCancelable(false)
.setPositiveButton("确定", null);
builder.create()
.show();
}
}
注意 在AndroidMainfest.xml下要有 <uses-permission android:name="android.permission.INTERNET"/>
在数据库是test2,表是test
注意:
当用模拟器的时候MainActivity.java
private static String url = "http://10.0.2.2/test.php";调用test.php对数据库进行操作。
当用手机运行app,访问局域网的电脑的时候
private static String url = "http://192.168.1.102:80/test.php"; 192.168.1.102是我电脑的ip地址,然后80是wampservel 的端口。
注意:当用手机的时候,如果系统是window7的时候,要把windows防火墙关掉,要不然访问不了。开始-控制面板-windows防火墙-关闭windows防火墙
如果不想关闭防火墙那就增加端口 开始-控制面板-windows防火墙-高级设置-
然后点击入站规则,新建规则
选择端口,下一步
选tcp,端口写80.
最后出现如下图情况,设置成功
出站规则和入站规则一样设置。
如果有问题的话可以参考 http://blog.csdn.net/zzq900503/article/details/11936379
如果设置后用手机访问,输入网址192.168.1.102:80 返回是403错误的话,那就是权限不够。
一,Apache部分:
路径:/wamp/bin/apache/Apache2.4.9/conf/httpd.conf
其中Apache版本号请按实际情况而定。将所有Directory段内的deny条件都替换修改为allow from all:
<directory>
Options FollowSymLinksAllowOverride None
Order deny,allow
Allow from all #以前是Deny from all
</directory>
二,phpmyadmin部分:
路径:/wamp/alias/phpmyadmin.conf
同理,将deny条件修改为allow from all:
......
## Controls who can get stuff from this server.
#
# onlineoffline tag - don't remove
Order Deny,AllowDeny from all
Allow from all #以前是Allow from 127.0.0.1
</directory>
最后重启所有服务,问题解决喽~
参考网上其他说的 http://shiove.com/shine/?p=237
最后演示效果如下
手机端:
PC端数据库: