to make it short, the next code
JavaScript
x
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
JavaScript
"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:
- Put
e.printStackTrace()
insidecatch
block. - Simply remove the
try-catch
and declarethrows the-relevant-exception-class
with the method signature.
To avoid SQL injection, you should use prepareStatement
as follows:
JavaScript
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.