如何使用PHP脚本和JSON从MySQL获取数据并将其存储到Java程序
我想创建一个Java应用程序,它将接收来自MySQL的数据并将其存储到列表中,但在开始时,将数据存储到JTextArea就可以了 我在localhost上有一个带有表的数据库,以及PHP脚本,当它被激活时,从表顺序中获取数据并以JSON格式返回数据如何使用PHP脚本和JSON从MySQL获取数据并将其存储到Java程序,java,php,mysql,json,Java,Php,Mysql,Json,我想创建一个Java应用程序,它将接收来自MySQL的数据并将其存储到列表中,但在开始时,将数据存储到JTextArea就可以了 我在localhost上有一个带有表的数据库,以及PHP脚本,当它被激活时,从表顺序中获取数据并以JSON格式返回数据 <?php /* * Following code will list all orders */ // array for JSON response $response = array(); // include db co
<?php
/*
* Following code will list all orders
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from orders table
$result = mysql_query("SELECT* FROM orders") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["orders"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$order = array();
$order["id"] = $row["id"];
$order["tablle"] = $row["tablle"];
$order["drink"] = $row["drink"];
$order["created_at"] = $result["created_at"];
// push single product into final response array
array_push($response["orders"], $order);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);;
}
?>
你得做几件事 从Java调用php脚本 为此,您需要知道脚本的URL是什么,包括协议、端口、主机和路径。换句话说,类似于:http://localhost:8000/orders.php. 一旦你有了这个URL,你就需要去访问它 将响应解析为JSON数据结构 您可以使用现有的库(如 使用JSONObject填充UI 了解如何显示数据,并在JTextArea上调用setText
我想您需要一个从Java到为php输出服务的服务器的HTTP客户端连接。如果您进行一些研究,您可以找到数百个库和实现方法。不要使用任何成功键,只要在没有结果时对空数组[]进行编码即可^^
package newpackage;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Prozor extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JTextArea ta = new JTextArea();
JButton dugme = new JButton("Get data");
public Prozor(){
this.setBounds(500, 200, 500, 500);
this.setTitle("naslov");
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(panel, BorderLayout.NORTH);
this.getContentPane().add(panel2, BorderLayout.SOUTH);
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
ta.setPreferredSize(new Dimension(450,400));
panel.add(ta);
panel2.add(dugme);
dugme.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(dugme)) {
}
}
public static void main(String[] args) {
Prozor p = new Prozor();
p.setVisible(true);
}
}