本文实例讲述了Android通过json向MySQL中写入数据的方法。,具体如下:

先说一下如何通过json将Android程序中的数据上传到MySQL中:

首先定义一个类JSONParser.Java类,将json上传数据的方法封装好,可以直接在主程序中调用该类,代码如下

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 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;

}

}

主程序中这样调用:

params = new ArrayList();

//这里可以替换成你自己程序中的一些键值对

params.add(new BasicNameValuePair("time", ""+time));

params.add(new BasicNameValuePair("lat", ""+lat));

params.add(new BasicNameValuePair("lon", ""+lon));

params.add(new BasicNameValuePair("encyptiontype",encyptiontype));

params.add(new BasicNameValuePair("rssi",rssi));

params.add(new BasicNameValuePair("name",name));

JSONParser jsonParser = new JSONParser();

//数据的php文件的路径

String url_up = "******/文件名字.php";

try{

JSONObject json = jsonParser.makeHttpRequest(url_up,"POST", params);

Log.v("uploadsucceed", "uploadsucceed");

}catch(Exception e){

e.printStackTrace();

}

最后就是定义一个接收数据的php文件:

// array for JSON response

//此处需要将数据库名和表明还有密码做相应修改,改成你自己的

$con = mysql_connect("localhost","root",null);

if (!$con) {

die('Could not connect:'.mysql_error() );

}

mysql_select_db("a0722152915", $con);

$response = array();

include("conn.php");

// check for required fields

if (isset($_POST['time']) && isset($_POST['lat']) && isset($_POST['lon'])&& isset($_POST['encyptiontype'])&& isset($_POST['rssi'])&& isset($_POST['name'])) {

$time = $_POST['time'];

$lat = $_POST['lat'];

$lon = $_POST['lon'];

$encyptiontype = $_POST['encyptiontype'];

$rssi = $_POST['rssi'];

$name = $_POST['name'];

$result = mysql_query("INSERT INTO wifi_state(time, lat, lon,encyptiontype,rssi,name) VALUES('$time', '$lat', '$lon','$encyptiontype','$rssi','$name')");

echo $result;

// check if row inserted or not

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 json mysql_Android通过json向MySQL中读写数据的方法详解【写入篇】相关推荐

  1. android json mysql_Android通过json向MySQL中读写数据的方法详解【读取篇】

    本文实例讲述了Android通过json向MySQL中读取数据的方法.分享给大家供大家参考,具体如下: 首先 要定义几个解析json的方法parseJsonMulti,代码如下: private vo ...

  2. MySQL中ESCAPE关键字的用法详解

    MySQL中ESCAPE关键字的用法详解 MySQL中ESCAPE关键字的用法详解 1. mysql转义概述 2. escape验证 MySQL中ESCAPE关键字的用法详解 1. mysql转义概述 ...

  3. webconfig的解决方案怎么添加_解决在Web.config或App.config中添加自定义配置的方法详解...

    文档从网络中收集,已重新整理排版 .word 版本可编辑 . 欢迎下载支持 . 1 word 版本可编辑 . 欢迎下载支持 . 解决在 Web.config 或 App.config 中添 加自定义配 ...

  4. java中迭代器要导包吗_java 中迭代器的使用方法详解

    java 中迭代器的使用方法详解 前言: 迭代器模式将一个集合给封装起来,主要是为用户提供了一种遍历其内部元素的方式.迭代器模式有两个优点:①提供给用户一个遍历的方式,而没有暴露其内部实现细节:②把元 ...

  5. php中this的使用技巧,JavaScript中this关键字使用方法详解

    JavaScript中this关键字使用方法详解 在面向对象编程语言中,对于this关键字我们是非常熟悉的.比如C++.C#和Java等都提供了这个关键字,虽然在开始学习的时候觉得比较难,但只要理解了 ...

  6. vue缓存服务器文件到本地,vue中,在本地缓存中读写数据的方法

    1.安装good-storage插件 cnpm i good-storage --save 2.读/写的方法 common/js/cache.js: import storage from 'good ...

  7. android 6.0 存储卡,Android 6.0区别U盘和SD卡设备的方法详解

    如下所示: public static boolean isSdcardExists(Context context) { StorageManager storageManager = Storag ...

  8. 在HTML文档中使用JavaScript的方法详解

    在HTML文档中使用JavaScript的方法详解 本文详细介绍,在HTML文档(也称为HTML页面或网页)中使用JavaScript脚本代码的多种方法. 假设要用JS生成字符☆直角三角形 实现Jav ...

  9. 无刷新跳转—关于history中pushState和replaceState方法详解

    〝 古人学问遗无力,少壮功夫老始成 〞 **关于history中pushState和replaceState方法详解,**常码字不易,出精品更难,没有特别幸运,那么请先特别努力,别因为懒惰而失败,还矫 ...

最新文章

  1. 在 Delphi 下使用 DirectSound (12): 测试失真效果器 IDirectSoundFXDistortion8
  2. android layout background,Android LinearLayout Gradient Background
  3. SQL Server 数据库的维护(四)__游标(cursor)
  4. Asterisk配置文件说明
  5. JS键盘事件最全keycode代码
  6. 内核参数 linux dd,Linux dd命令使用示例
  7. C++第一个综合项目
  8. Übersicht for mac(自定义桌面工具)v1.6(68)最新版
  9. Jmeter中主要管理器功用
  10. oracle_分区表的新增、修改、删除、合并。普通表转分区表方法
  11. IMSIDesign.TurboCAD.Designer.v14
  12. c语言创建一个bat文件内容,基础教程:如何创建批处理文件
  13. 调试The Annotated Transformer
  14. Turing Tape (推公式 模拟)
  15. 吉林银行2021年上半年经营成果丰硕 支持实体经济能力显著增强
  16. 公众号开发(三)----接收事件推送之关注/取消关注事件
  17. linux研发工程师笔试题,2015-8-29阿里校园招聘研发工程师笔试题
  18. Scheduled定时任务的使用
  19. 关于打架以及打架的策略的问题
  20. 阿里浅尝元宇宙成功了吗?

热门文章

  1. 1 张图,拆解阿里 P8高级架构师必会技术栈!
  2. 搞个996或247,你的团队就是互联网团队了?
  3. linux sed命令新文件名,linux中sed命令批量修改
  4. mysql 编码 windows_修改mysql默认编码的方法(windows环境)
  5. python3.5 mysql 库_Python 3.5 连接Mysql数据库(pymysql 方式)
  6. resnet50 自定义
  7. torch模拟sigmoid
  8. g++ 编译pybind
  9. python turtle 画闹钟
  10. pytorch one-hot转数组