- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个 Android 应用程序,它通过 HTTP POST 方法将数据发送到 PHP 脚本,并试图解析数据以存储到 MySQL 中。 Android 应用程序不是我编写的,但我可以访问下面包含的源代码;它发送打包为 JSON 数组的数据。我的 PHP 脚本现在尝试将数据同时放入文本文件和 MySQL 数据库中:
<?php
$con=mysqli_connect("localhost","dbname","dbpassword","table");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL DB: " . mysqli_connect_error();
}
$filename = __DIR__.DIRECTORY_SEPARATOR."jsontest.txt";
$postdata = file_get_contents("php://input");
$data = json_decode($postdata, true);
//if (array_key_exists('records', $data) && is_array($data['records'])) {
//above if loop threw warning "array_key_exists() expects parameter 2 to be array, null given"
if (is_array($data['records'])) {
foreach ($data['records'] as $record) {
$name = $record['name'];
$value = $record['value'];
$event = $record['event'];
$timestamp = $record['timestamp'];
file_put_contents($filename, "$name -> $value with event: $event at $timestamp\n", FILE_APPEND);
mysqli_query($con,"INSERT INTO `Driving Data`(`Name`, `Value`, `Event`, `Timestamp`) VALUES ($name, $value, $event, $timestamp)");
}
}
mysqli_close($con);
?>
文本文件打印出我告诉它的所有数据。但是,数据库根本不会更新。数据库设置如下:
CREATE TABLE `Driving Data` (
`Name` varchar(75) NOT NULL,
`Value` varchar(40) NOT NULL,
`Event` varchar(20) NOT NULL,
`Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=latin1
这是 JSON 数据的示例:
{"records":[{"name":"accelerator_pedal_position","value":15.400001,"timestamp":1367598908.278000},{"name":"engine_speed","value":1716.0,"timestamp":1367598908.285000},{"name":"vehicle_speed","value":32.040001,"timestamp":1367598908.290000},{"name":"brake_pedal_status","value":false,"timestamp":1367598908.293000},{"name":"fuel_consumed_since_restart","value":0.147325,"timestamp":1367598908.301000},{"name":"transmission_gear_position","value":"third","timestamp":1367598908.304000},{"name":"steering_wheel_angle","value":-2.3733,"timestamp":1367598908.307000},{"name":"fuel_consumed_since_restart","value":0.14745,"timestamp":1367598908.314000},{"name":"transmission_gear_position","value":"third","timestamp":1367598908.317000},{"name":"door_status","value":"driver","event":false,"timestamp":1367598908.320000},{"name":"door_status","value":"passenger","event":false,"timestamp":1367598908.326000},{"name":"door_status","value":"rear_left","event":false,"timestamp":1367598908.329000},{"name":"door_status","value":"rear_right","event":false,"timestamp":1367598908.331000},{"name":"odometer","value":0.0,"timestamp":1367598908.338000},{"name":"high_beam_status","value":false,"timestamp":1367598908.341000},{"name":"steering_wheel_angle","value":-2.3733,"timestamp":1367598908.343000},{"name":"engine_speed","value":1716.0,"timestamp":1367598908.351000},{"name":"powertrain_torque","value":74.0,"timestamp":1367598908.358000},{"name":"accelerator_pedal_position","value":12.1,"timestamp":1367598908.364000},{"name":"latitude","value":42.293911,"timestamp":1367598908.367000},{"name":"longitude","value":-83.238762,"timestamp":1367598908.376000},{"name":"engine_speed","value":1718.0,"timestamp":1367598908.380000},{"name":"vehicle_speed","value":32.200001,"timestamp":1367598908.382000},{"name":"brake_pedal_status","value":false,"timestamp":1367598908.391000},{"name":"transmission_gear_position","value":"third","timestamp":1367598908.393000}]}
所以我对 PHP 比较陌生,我似乎无法弄清楚问题是什么(即为什么数据库没有用这些值更新但它仍然可以将它们写到文本文件中。供引用,下面是用于将数据发送到 Web 服务器的 Android 代码(我无法更改它):
public class UploaderSink extends ContextualVehicleDataSink {
private final static String TAG = "UploaderSink";
private final static int UPLOAD_BATCH_SIZE = 25;
private final static int MAXIMUM_QUEUED_RECORDS = 5000;
private final static int HTTP_TIMEOUT = 5000;
private URI mUri;
private BlockingQueue<String> mRecordQueue =
new LinkedBlockingQueue<String>(MAXIMUM_QUEUED_RECORDS);
private Lock mQueueLock = new ReentrantLock();
private Condition mRecordsQueued = mQueueLock.newCondition();
private UploaderThread mUploader = new UploaderThread();
/**
* Initialize and start a new UploaderSink immediately.
*
* @param uri the URI to send HTTP POST requests to with the JSON data.
*/
public UploaderSink(Context context, URI uri) {
super(context);
mUri = uri;
}
public UploaderSink(Context context, String path) throws DataSinkException {
this(context, uriFromString(path));
}
@Override
public void stop() {
super.stop();
mUploader.done();
}
public boolean receive(RawMeasurement measurement) {
String data = measurement.serialize(true);
mRecordQueue.offer(data);
if(mRecordQueue.size() >= UPLOAD_BATCH_SIZE) {
mQueueLock.lock();
mRecordsQueued.signal();
mQueueLock.unlock();
}
return true;
}
/**
* Returns true if the path is not null and if it is a valid URI.
*
* @param path a URI to validate
* @return true if path is a valid URI.
*
*/
public static boolean validatePath(String path) {
if(path == null) {
Log.w(TAG, "Uploading path not set (it's " + path + ")");
return false;
}
try {
uriFromString(path);
return true;
} catch(DataSinkException e) {
return false;
}
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("uri", mUri)
.add("queuedRecords", mRecordQueue.size())
.toString();
}
private static URI uriFromString(String path) throws DataSinkException {
try {
return new URI(path);
} catch(java.net.URISyntaxException e) {
throw new UploaderException(
"Uploading path in wrong format -- expected: ip:port");
}
}
private static class UploaderException extends DataSinkException {
private static final long serialVersionUID = 7436279598279767619L;
public UploaderException() { }
public UploaderException(String message) {
super(message);
}
}
private class UploaderThread extends Thread {
private boolean mRunning = true;
public UploaderThread() {
start();
}
public void run() {
while(mRunning) {
try {
ArrayList<String> records = getRecords();
String data = constructRequestData(records);
HttpPost request = constructRequest(data);
makeRequest(request);
} catch(UploaderException e) {
Log.w(TAG, "Problem uploading the record", e);
} catch(InterruptedException e) {
Log.w(TAG, "Uploader was interrupted", e);
break;
}
}
}
public void done() {
mRunning = false;
}
private String constructRequestData(ArrayList<String> records)
throws UploaderException {
StringWriter buffer = new StringWriter(512);
JsonFactory jsonFactory = new JsonFactory();
try {
JsonGenerator gen = jsonFactory.createJsonGenerator(buffer);
gen.writeStartObject();
gen.writeArrayFieldStart("records");
Iterator<String> recordIterator = records.iterator();
while(recordIterator.hasNext()) {
gen.writeRaw(recordIterator.next());
if(recordIterator.hasNext()) {
gen.writeRaw(",");
}
}
gen.writeEndArray();
gen.writeEndObject();
gen.close();
} catch(IOException e) {
Log.w(TAG, "Unable to encode all data to JSON -- " +
"message may be incomplete", e);
throw new UploaderException();
}
return buffer.toString();
}
private HttpPost constructRequest(String data)
throws UploaderException {
HttpPost request = new HttpPost(mUri);
try {
ByteArrayEntity entity = new ByteArrayEntity(
data.getBytes("UTF8"));
entity.setContentEncoding(
new BasicHeader("Content-Type", "application/json"));
request.setEntity(entity);
} catch(UnsupportedEncodingException e) {
Log.w(TAG, "Couldn't encode records for uploading", e);
throw new UploaderException();
}
return request;
}
private void makeRequest(HttpPost request) throws InterruptedException {
HttpParams parameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(parameters, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(parameters, HTTP_TIMEOUT);
final HttpClient client = new DefaultHttpClient(parameters);
try {
HttpResponse response = client.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_CREATED) {
Log.w(TAG, "Got unxpected status code: " + statusCode);
}
} catch(IOException e) {
Log.w(TAG, "Problem uploading the record", e);
try {
Thread.sleep(5000);
} catch(InterruptedException e2) {
Log.w(TAG, "Uploader interrupted after an error", e2);
throw e2;
}
}
}
private ArrayList<String> getRecords() throws InterruptedException {
mQueueLock.lock();
if(mRecordQueue.isEmpty()) {
// the queue is already thread safe, but we use this lock to get
// a condition variable we can use to signal when a batch has
// been queued.
mRecordsQueued.await();
}
ArrayList<String> records = new ArrayList<String>();
mRecordQueue.drainTo(records, UPLOAD_BATCH_SIZE);
mQueueLock.unlock();
return records;
}
}
最佳答案
尝试将 unix 时间戳转换为 mysql 时间戳
if (is_array($data['records'])) {
foreach ($data['records'] as $record) {
$name = $record['name'];
$value = $record['value'];
$event = $record['event'];
$timestamp = date('Y-m-d H:i:s',$record['timestamp']);
file_put_contents($filename, "$name -> $value with event: $event at $timestamp\n", FILE_APPEND);
mysqli_query($con,"INSERT INTO `Driving Data`(`Name`, `Value`, `Event`, `Timestamp`) VALUES ($n
ame, $value, $event, $timestamp)");
}
}
关于PHP 将 JSON 数据从 Android 插入 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16684188/
我有 512 行要插入到数据库中。我想知道提交多个插入内容是否比提交一个大插入内容有任何优势。例如 1x 512 行插入 -- INSERT INTO mydb.mytable (id, phonen
已经提出了类似的问题,但由于它总是取决于,我单独询问我的具体情况。 我有一个网站页面,显示来自数据库的一些数据,要从该数据库生成数据,我必须执行一些相当复杂的多连接查询。 数据每天(每晚)更新一次。
我正在使用 MongoDb 和 MySQL 的 python 连接器 pymongo 和 pymysql 测试 MongoDb 和 MySQL,特别是插入功能。 pymongo版本是3.4,pymys
从 C# 应用程序插入大型数组(10M 元素)的最快方法是什么? 到目前为止,我使用的是批量插入。 C# 应用程序生成一个大文本文件,我使用 BULK INSERT 命令加载它。出于好奇,我编写了一个
我编写了一个枚举类型,当我为它运行我创建的 JUnit 测试时会出现以下语法错误: java.lang.Error: Unresolved compilation problems: Synt
我正在尝试创建一个程序,它将单词列表作为输入,并将它们排序为二叉树,以便能够找到它们,例如像字典。这是我到目前为止所做的,但是 newEl -> el = input; 出现段错误,我知道这是因为它试
你好 我有编译这个问题 \begin{equation} J = \sum_{j=1}^{C} \end{equation} 我不断收到错误 missing $ inserted 这很奇怪,因
我需要使用 LINQ to SQL 将记录插入到没有主键的表中。 table 设计得很差;我无法控制表结构。该表由几个 varchar 字段、一个文本字段和一个时间戳组成。它用作其他实体的审计跟踪。
我正在尝试使用 itextsharp 创建 Pdf。我添加了一张包含两列的表格,其中一列包含文本和其他图像。我想要恒定的图像大小 如果另一个单元格中的文本增加并且其他单元格中的图像大小不同,我的图像会
我想把 calory 作为 fruits 的第一个值,我做不到,有人能帮忙吗? $sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
我有一个包含季度观察结果的 data.frame。我现在想插入每月值(首选三次,线性很好)。中间目标应该是使用 DATE 创建一个 data.frame作为所有每月观察的索引和缺失值。 谷歌搜索表明我
我想知道是否有办法在值列表中使用“插入”。我正在尝试这样做: insert into tblMyTable (Col1, Col2, Col3) values('value1', value
我想让人们能够在他们的网站中插入单个 Javascript 行,这实际上允许我插入包含我网站内容的固定大小的 IFRAME。它实际上是一个小部件,允许他们搜索我的网站或接收其他信息。这可能吗? 最佳答
我有一个包含时间的表,列名为 time,数据类型为 Date。 在 asp.net 中,我想要一个查询插入日期,另一个查询则在 2 个日期之间进行选择。 我已经尝试过这个: string data =
这是我的代码: create or replace trigger th after insert on stock for each row declare sqty number;
这是一个带有具体示例的通用问题。 我有一个包含三个字段(流派 ID (PK IDENTITY)、流派和子流派)的表。该表对(流派,子流派)组合具有唯一约束。 我想知道如何修改存储过程以在表中不存在时插
因此,我正在遍历二叉树,节点包含字符串,以及读取文件时该字符串是否出现多次。我只查找读取文件时出现次数最多的前 10 个单词,因此本质上我只是比较 int 值。 我的问题是我正在尝试找出一种有效的方法
我有一张机票和行李 map , 每张门票必须是唯一的,并且必须与 map 上的位置相对应 是否可以仅更改行李(m_bagage->秒)而不更改 key ? std::unordered_map m_c
我正在使用 jdbc 驱动程序做一个示例项目。我的问题是,如果我在 2 文本字段中输入空值。 null 不应该加载到数据库中吗?有没有办法避免在数据库中插入空字段?任何帮助将不胜感激。 //Execu
我想知道 SSIS 中是否有特定的插入或更新选项。 如果我想让程序检查它是更新还是插入,我是否必须做一些编码?或者是否可以启用一个选项,以便它会自行检查 PK 是否存在,然后更新,否则插入? 亲切的问
我是一名优秀的程序员,十分优秀!