将java与本地主机连接,代码有问题

4nkexdtk  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(309)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

上个月关门了。
改进这个问题
简而言之,下一个代码

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”我有驱动程序连接器
当然还有数据库

5vf7fwbs

5vf7fwbs1#

除非你的mysql服务器在端口上运行, 3306 ,您必须始终提到端口,例如,您的连接参数应该是

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

哪里 1234 是端口号。
您还应执行以下操作之一以查看错误消息:
e.printStackTrace() 内部 catch 阻止。
只需移除 try-catch 并宣布 throws the-relevant-exception-class 方法签名。
为了避免sql注入,应该使用 prepareStatement 具体如下:

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

最后,确保关闭 PreparedStatement 以及 ResultSet . 为了自动完成,可以使用try with resources。

相关问题