使用 PHP 从 Java 连接到 MySQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13506363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:01:08  来源:igfitidea点击:

Connecting to MySQL from Java using PHP

javaphpmysql

提问by Rajesh

I'm having a weird problem of connection between Java, PHP and MySQL.

我在 Java、PHP 和 MySQL 之间的连接有一个奇怪的问题。

I'm not having direct access to my MySQL database on the webserver through Java. So, I converted the mechanism to run a PHP script, which does the job for me and return the results to my Java Application.

我无法通过 Java 直接访问网络服务器上的 MySQL 数据库。因此,我将机制转换为运行 PHP 脚本,该脚本为我完成工作并将结果返回到我的 Java 应用程序。

It's working pretty fine for most of the queries. But I'm not getting expected results when the queries include character fields in the query.

对于大多数查询,它工作得很好。但是当查询在查询中包含字符字段时,我没有得到预期的结果。

I include the PHP and Java Code snippets for reference.

我提供了 PHP 和 Java 代码片段以供参考。

Please find me the thing, where I'm doing wrong...

请帮我找到我做错的地方...

PHP Script on the server...

服务器上的 PHP 脚本...

<?php
$query=$_POST["query"];
echo" Query = ".$query."\n";
if($query){
$link=mysql_connect("mysql2.000webhost.com","a7946109_other","mypassword");
if($link){
mysql_select_db("a7946109_other");
$result=mysql_query($query);
if($result){
while($row=mysql_fetch_row($result)){ // for each row in results
foreach($row as $value){                           // for each column in row
echo "\t".$value;
}
echo"\n";
}
}
}else{
echo " MySQL connect failed ! \n";
}
}else{
echo " No Query ! \n";
}
exit();  // exit without auto_append_file
?>

Java Program...

Java程序...

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.applet.*;
import java.security.*;

public class MySQL_POST {
    public static void main(String r[]){
    HttpURLConnection conn=null;
    try{
    URL url=new URL("mywebsite.com/postdb.php");
    String agent="Applet";
    String query="query=" + r[0];
    String type="application/x-www-form-urlencoded";
    conn=(HttpURLConnection)url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty( "User-Agent", agent );
    conn.setRequestProperty( "Content-Type", type );
    conn.setRequestProperty( "Content-Length", ""+query.length());

    OutputStream out=conn.getOutputStream();
    out.write(query.getBytes());
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    while((inputLine=in.readLine())!=null){
        System.out.print(inputLine+"\n");
    };
    in.close();
    int rc = conn.getResponseCode();
    System.out.print("Response Code = "+rc+"\n");
    String rm=conn.getResponseMessage();
    System.out.print("Response Message = "+rm+"\n");
    }catch(Exception e){
    e.printStackTrace();
    }finally{
    conn.disconnect();
    }
    }

    }

I Have a table named TEST, with fields SID INT(3), SNAME VARCHAR(20), SLNAME VARCHAR(20)

我有一个名为 TEST 的表,其字段为 SID INT(3)、SNAME VARCHAR(20)、SLNAME VARCHAR(20)

It has got two entries in the table.

它在表中有两个条目。

When I execute the following queries using Java, I get different types of outputs as follows.

当我使用 Java 执行以下查询时,我得到如下不同类型的输出。

> java MYSQL_POST "SELECT * FROM TEST"

 Query = SELECT * FROM TEST
 1 Test1 Test1L
 2 Test2 Test2L
Response Code = 200
Response Message = OK

Which is want I expected.

这是我所期望的。

> java MYSQL_POST "SELECT SNAME FROM TEST WHERE SID = 1"

 Query = SELECT SNAME FROM TEST WHERE SID = 1
 Test1
Response Code = 200
Response Message = OK

Which is also as I expected.

这也符合我的预期。

Here comes the weird one.

奇怪的来了。

> java MYSQL_POST "SELECT SID FROM TEST WHERE SNAME = 'Test1'"

  Query = SELECT SID FROM TEST WHERE SNAME = \'Test1\'
 Response Code = 200
 Response Message = OK

Which doesn't result in any result, which as expected should be 1

这不会导致任何结果,正如预期的那样 1

The queries, which involve characters like SNAME = 'Test1'or any other or not working. Except these queries, others are fine.

查询,涉及字符 likeSNAME = 'Test1'或 any other or not working. 除了这些查询,其他都很好。

Please anyone help me in fixing this.

请任何人帮我解决这个问题。

Thanks in advance.

提前致谢。

回答by Kaivosukeltaja

The server running your PHP script has the magic quotessetting on. This automatically escapes quotes in incoming data from POST/GET/etc with backslashes. Using magic quotes is not recommended and they have been deprecated since PHP 5.4.0. Disable themand add proper sanitation to your code - it's a huge security risk to execute queries straight from external input.

运行您的 PHP 脚本的服务器开启了魔术引号设置。这会使用反斜杠自动转义来自 POST/GET/etc 的传入数据中的引号。不推荐使用魔术引号,并且自 PHP 5.4.0 起它们已被弃用。禁用它们并为您的代码添加适当的卫生 - 直接从外部输入执行查询是一个巨大的安全风险。