【问题标题】:Update SQL using GET request in Java在 Java 中使用 GET 请求更新 SQL
【发布时间】:2014-01-08 21:56:00
【问题描述】:

我正在尝试在 java 中更新一个 sql 数据库,但它只适用于导航器。我正在为此使用 GET 请求,因为主机不允许我激活 sql 远程访问。

这是java函数:

public static void insertScore(String user, boolean win){
        URL url;
        HttpURLConnection connection=null; 
        try {
            url = new URL("http://mypage/insert.php?user="+user+"&win="+win);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
        } catch (MalformedURLException ex) {
            Logger.getLogger(SQL.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

还有insert.php文件,这个文件还可以,不过如果对你有帮助的话:

<?php
if($_GET["win"]=='true'){
$sql="UPDATE Score SET  `Win` =  `Win` +1 WHERE  `User` = '".$_GET['user']."'";
}
else{ 
$sql="UPDATE Score SET  `Lose` =  `Lose` +1 WHERE  `User` = '".$_GET['user']."'";
}

$link = mysqli_connect('myhost','myuser','mypassword','mydb'); //everything ok here
if (!$link) {
    die('Error: ' . mysql_error());
}
$result=$link->query($sql);
?>

当我将链接粘贴到 safari http://mypage/insert.php?user=Steve&amp;win=true 中时,Sql 数据库会正确更新,但我不知道如何使用 Java 执行此操作,它不会更新数据库中的任何内容...

【问题讨论】:

  • 请,在您编写任何更多 SQL 接口代码之前,您必须阅读 proper SQL escaping 以避免严重的 SQL injection bugs。使用mysqli 时,您应该使用参数化查询和bind_param 将用户数据添加到您的查询中。 避免使用字符串插值来完成此操作。
  • (另外,即使转义是固定的,这个系统非常容易作弊,它违反了 GET 幂等的规则。我建议看看现有的 RPC/WebAPI框架[有一个 Java 客户端和 PHP 提供程序]。)

标签: java mysql sql get


【解决方案1】:

假设您正在使用DAO 设计模式,使用此代码您可以更新数据库中的一行:

public class UserDao { 
// you need to call your Singleton Connection class:
  Connection con = MyConnection.getInstanceOf();

   // and then you write a method to update your object, here I'm updating a User Object:
    public void updateUser(User user) {
         try {
            String sql= "Update User  set username='"+user.getUserName()+"',score='"+user.getScore()+"' where userid='"+user.getUserId()+"'";


            Statement ste= con.createStatement();
            ste.executeUpdate(sql);

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

【讨论】:

    【解决方案2】:

    已解决,下载了一个库,一切正常 代码是:

    public static void insertScore(String user, boolean win){
            final WebClient webClient = new WebClient();
            try {
                final HtmlPage page1 = webClient.getPage("http://mywebpage/insert.php?user="+user+"&win="+win);
            } catch (IOException | FailingHttpStatusCodeException ex) {
                Logger.getLogger(SQL.class.getName()).log(Level.SEVERE, null, ex);
            }
            webClient.closeAllWindows();
        }
    

    官网:http://htmlunit.sourceforge.net/gettingStarted.html

    【讨论】:

    • IMO 你正在使用坦克杀死蚂蚁
    • 这是我找到的第一个解决方案:/有什么改进的建议吗?
    • 我改了!现在可以了吗?
    【解决方案3】:

    有了这个,我不使用坦克来猎杀蚂蚁(我认为)

    public static void insertScore(String user, boolean win){
    
    
    
        URI uri;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            uri = new URIBuilder()
                    .setScheme("http")
                    .setHost("mypage")
                    .setPath("/insert.php")
                    .setParameter("user", user)
                    .setParameter("win", win+"")
                    .build();
            System.out.println(uri);
            HttpGet httpget = new HttpGet(uri);
            CloseableHttpResponse response =httpclient.execute(httpget);
            response.close();
        } catch (URISyntaxException | IOException ex) {
            Logger.getLogger(SQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多