【问题标题】:Connecting Java with a localhost, problem with my code [closed]将Java与本地主机连接,我的代码有问题[关闭]
【发布时间】:2021-03-22 01:18:28
【问题描述】:

简而言之,下一个代码

    import java.sql.*;

    public class Prueba{`
    public static String user="Boss";
    public static String pass="123456";

    public static void main(String args[]) {

     try {
       Connection cn=DriverManager.getConnection("jdbc:mysql://localhost/bd_ds", "root", "");

        PreparedStatement pst=cn.prepareStatement(
        "select tipo_nivel, estatus from usuarios where username =' "+user
        + " '  and password ='  " + pass+ " '  ");
        
        ResultSet rs=pst.executeQuery();

        System.out.println(rs.next());

        }catch(Exception e) {}
    }
    }
    

变量“rs.next()”应该返回“true” 我已经打开了 XAMPP、apache 和“mysql” 我有驱动连接器
当然还有数据库

【问题讨论】:

  • 您不应将值连接到查询字符串中,这会使您的代码容易受到 SQL 注入的攻击。使用带参数的准备好的语句。然而,主要问题是您在用户名和密码之前添加了空格。数据库存储用户名'x',但您的查询要求输入用户名' x '(注意空格),通常会忽略尾随空格,但不会忽略前导空格。所以找不到用户' x',因为它只知道用户'x'。与密码相同(顺便说一句,这也是一个安全问题,你应该散列密码)

标签: java mysql localhost


【解决方案1】:

除非您的 MySQL 服务器在端口 3306 上运行,否则您必须始终提及端口,例如您的连接参数应该类似于

"jdbc:mysql://localhost:1234/bd_ds", "root", ""

其中1234 是端口号。

您还应该执行以下操作之一以查看错误消息:

  1. e.printStackTrace() 放入catch 块中。
  2. 只需删除try-catch 并使用方法签名声明throws the-relevant-exception-class

为避免SQL injection,您应该使用prepareStatement,如下所示:

cn.prepareStatement(
        "select tipo_nivel, estatus from usuarios where username =? and password =?");
cn.setString(1, user);
cn.setString(2, pass);

最后,确保关闭PreparedStatementResultSet。为了让它自动完成,你可以使用try-with-resources

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-07
    • 2011-05-09
    • 2016-02-01
    • 2016-11-15
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2016-05-16
    相关资源
    最近更新 更多