Skip to content
Advertisement

Connecting Java with a localhost, problem with my code [closed]

to make it short, the next code

    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) {}
    }
    }
    

the variable “rs.next()” should return “true” i have already turn on XAMPP, apache and “mysql” i have the driver connector
and of course the database

Advertisement

Answer

Unless your MySQL server is running on port, 3306, you must always mention the port e.g. your connection parameters should be something like

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

where 1234 is the port number.

You should also do one of the following to see the error message:

  1. Put e.printStackTrace() inside catch block.
  2. Simply remove the try-catch and declare throws the-relevant-exception-class with the method signature.

To avoid SQL injection, you should use prepareStatement as follows:

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

Finally, make sure to close the PreparedStatement and ResultSet. In order to get it done automatically, you can use try-with-resources.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement