有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的字符串用法

考虑将下面的代码中的URL分配给一个字符串,比如说

String link = "http://www.topix.com/rss/city/ellensburg-wa";

我应该如何在下面的代码中使用字符串而不是URL本身

注意:我是java的初学者

 stmt.executeQuery("select url from urls where url='http://www.topix.com/rss/city/ellensburg-wa'");

 stmtR.executeUpdate("insert into urls values(21211,'http://www.topix.com/rss/city/ellensburg-wa','source',1,0)"

共 (4) 个答案

  1. # 1 楼答案

    stmt.executeQuery("select url from urls where url='" + link + "'");
    
    stmtR.executeUpdate("insert into urls values(21211,'" + link + "','source',1,0)"
    

    +是Java的字符串连接运算符
    见:http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html


    注意

    你应该考虑使用准备好的语句(见其他的答案),如果你要用这个SQL查询。p>

  2. # 2 楼答案

    您可以这样做:

    stmt.executeQuery("select url from urls where url='"+link+"'");
    
  3. # 3 楼答案

    这一次我得付2便士

    从来没有 使用字符串连接和SQL

    (好的,可能应该理解为从不使用sting连接和用户输入)

    遵循上面给出的关于使用准备好的语句的建议

    想想如果使用字符串连接和SQL,当一些讨厌的用户进入链接时会发生什么

    x'; DROP TABLE urls; --
    

    你的代码看起来像

    stmt.executeQuery("select url from urls where url='x'; DROP TABLE urls; --'");
    

    认真地说,甚至不要编写这样的原型,坏代码总是坏代码,最终会被使用。你不想因为写了十大漏洞之一而被解雇,是吗? www.drdobbs。com/web开发/224400744

    转到本网站,了解更多SQL字符串连接不好的示例和原因 http://unixwiz.net/techtips/sql-injection.html

  4. # 4 楼答案

    如果您想创建一个好的查询,请使用prepared statement

    PreparedStatement insertUrlStatement = con.prepareStatement("INSERT INTO urls VALUES(?, ?, ?, ?)");
    //Replace the **first** "?" by an "id" variable content (containing an **int**)
    insertUrlStatement.setInt(1, id);
    //Replace the **second** "?" by the "url" variable content (containing a **String**)
    insertUrlStatement.setString(2, url);
    //Two other setXxx();
    insertUrlStatement.executeUpdate()