0

我正在尝试从我的 Java 程序中调用一些 PHP 脚本,以便查询/修改我的数据库。我对数据库完全陌生,不知道发生了什么。

我正在尝试从 java 中调用以下脚本。

脚本

<?php
include('test.php');

define("HOST", "localhost");

define("USERNAME", "xxxx");

define("PASSWORD", "xxxx");

define("DATABASE", "project_database");

mysql_connect(HOST, USERNAME, PASSWORD);

mysql_select_db(DATABASE);

?>

Java 代码

 public static String excutePost(String targetURL, String urlParameters)
    {
      URL url;
      HttpURLConnection connection = null;  
      try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", 
             "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + 
                 Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");  

        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                    connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();

        //Get Response  
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer(); 
        while((line = rd.readLine()) != null) {
          response.append(line);
          response.append('\r');
        }
        rd.close();
        return response.toString();

      } catch (Exception e) {

        e.printStackTrace();
        return null;

      } finally {

        if(connection != null) {
          connection.disconnect(); 
        }
      }
    }

目标网址应该是什么?

4

2 回答 2

3

如果要调用新进程,请参阅java.lang.Process

然而,Java 能够通过JDBC直接与您的数据库对话,这是我强烈推荐的方法。您不必产生新的流程或用一种以上的语言实现您的解决方案,您可以利用众多与 JDBC 相关的框架来让您的生活重新焕发生机。数据库访问相当容易。

于 2013-02-07T17:36:33.533 回答
0

您需要指定页面的链接,可能类似于 '/localhost/yourPageInPhp.php

我假设您需要执行脚本并在 Java 中显示其输出

于 2013-02-07T17:38:43.313 回答