繁体   English   中英

Android-将数据从Android SQLite DB发布到localhost服务器上的MySQL DB

[英]Android - posting data from Android SQLite DB to MySQL DB on localhost server

我正在做一些分配,并且需要在本地服务器上启用SQLite DB数据与MySQL DB的同步。 单击按钮时,需要“收集”来自SQLite的数据,将其转换为JSON并发送到localhost MySQL DB并插入其中。 我制作了Activity来处理这项工作,根据学院的示例制作了一些PHP,并在运行wamp服务器的地方制作了需要存储数据的数据库。 在我的localhost上,数据库命名为“ employees_db”,其中的表名为“ employees”。 这是我制作的android studio中的代码:

package com.EmDatabase;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataSyncManager extends Activity {

Database db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sync_options);
    db = new Database(this);
    db.getWritableDatabase();
}

public void syncToServer(View v) throws JSONException {
    List<Employe> employes = db.selectAll();
    JSONObject objEmployes = new JSONObject();
    JSONArray employesData = new JSONArray();
    for (Employe employe : employes) {
        int id = employe.getId();
        String name = employe.getName();
        String surname = employe.getSurname();
        int age = employe.getAge();
        String company = employe.getCompany();
        String wtype = employe.getWorktype();
        JSONObject empData = new JSONObject();
        empData.put("id", id);
        empData.put("name", name);
        empData.put("surname", surname);
        empData.put("age", age);
        empData.put("company", company);
        empData.put("worktype", wtype);
        employesData.put(empData);
    }
    objEmployes.put("all_employes", employesData);
    String result = objEmployes.toString();
    System.out.println(result);
    UploadJsonStringTask task = new UploadJsonStringTask();
    task.execute(
            new String[] { "http://10.0.2.2/employes_db/register.php", result}
    );
}

public void syncFromServer(View v) {

}

private class UploadJsonStringTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String response = "";
        Map<String,String> queries = new HashMap<String, String>(1);
        queries.put("all_employes", params[1]);
        try {
            response += postHttpContent(params[0],queries);
        } catch (IOException e) {
            Log.e("error", e.toString());
        }
        return response;
    }
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    }

    public String postHttpContent(String urlString, Map<String, String> queries) throws IOException {
        String response = "";
        URL url = new URL(urlString);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String postData = "";
        for (String key : queries.keySet()) {
            postData += "&" + key + "=" + queries.get(key);
        }
        postData = postData.substring(1);
        DataOutputStream postOut = new DataOutputStream(httpConnection.getOutputStream());
        postOut.writeBytes(postData);
        postOut.flush();
        postOut.close();

        int responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
            throw new IOException();
        }
        return response + " *** Uploaded!";
    }
}

public void goBack(View v) {
    Intent in= new Intent(DataSyncManager.this,MainActivity.class);
    startActivity(in);
}

}

这是我制作并插入到wampserver / www / employes_db(register.php)中的PHP文件:

<?php
$id = 0;
$name = "";
$surname = "";
$age = 0;
$company = "";
$worktype = "";
$conn = new mysqli("localhost","root","","employes_db");
$conn->query("insert into employes values (null,'".$_POST['id']."','".$_POST['name']."','".$_POST['surname']."','".$_POST['age']."','".$_POST['company']."','".$_POST['worktype']."')");
if(!$conn->error) echo "{status:0}"; else echo "{status:-1}";
?>

当我启动应用程序时,在SQLite数据库中插入一行,然后单击“同步”按钮,然后打开“ localhost / employes_db / register.php”,我收到“错误”->注意:未定义的索引:C:\\ wamp64 \\ www \\中的id第9行上的employeees_db \\ register.php <-其余列(名称,姓氏,年龄,公司,wtype)的错误相同。 有人可以帮忙,我的错误在哪里?

Undefined index: id表示$_POST['id']不存在。 第一个错误是您使用$_POST检索数据,而是使用$_GET 第二个是使用$_GET检索数据,您必须这样访问URL: localhost/register.php?id=myID


在您的情况下,您是通过HTTPPost发送数据的,因此只需使用file_get_contents('php://input')来获取JSON字符串,解码接收到的JSON数据( json_decode($myJSONString) ),然后将其发送到第二个数据库。

编辑
如果我正确理解了您的问题,您可以这样做:

// get all employees from your first database and write them into a JSONArray

List<Employe> employes = db.selectAll();
JSONObject objEmployes = new JSONObject();
JSONArray employesData = new JSONArray();
for (Employe employe : employes) {
    int id = employe.getId();
    String name = employe.getName();
    String surname = employe.getSurname();
    int age = employe.getAge();
    String company = employe.getCompany();
    String wtype = employe.getWorktype();
    JSONObject empData = new JSONObject();
    empData.put("id", id);
    empData.put("name", name);
    empData.put("surname", surname);
    empData.put("age", age);
    empData.put("company", company);
    empData.put("worktype", wtype);
    employesData.put(empData);
}

// open connection
URL url = new URL("yourUrl.com/yourPhpScript.php");
url.openConnection();

// send JSONArray to your second database
String dataToSend = employesData.toString();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(dataToSend);
writer.flush();
writer.close();

PHP脚本:

<?php
// connect to database
$link = mysqli_connect($hostname, $username, $password);
mysqli_select_db($link, "myDatabase");

// get the JSONArray the app sends
$contents = file_get_contents('php://input');

$jsonArray = json_decode($contents, true);
$jsonCount = count($jsonArray);

for ($i = 0; $i < $jsonCount; $i++) {
    $item = $jsonArray[$i];
    $itemName = utf8_decode($item['name']);
    // parse the other json attributes here like the one above

    $query = "INSERT INTO employees VALUES('$itemName', 'addOtherValuesHere...')";
    mysqli_query($link, $query);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM