将 Java 连接到本地主机,我的代码有问题
Connecting Java with a localhost, problem with my 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) {}
}
}
变量“rs.next()”应该return“真”
我已经打开 XAMPP、apache 和“mysql”
我有驱动连接器
当然还有数据库
除非您的 MySQL 服务器在 运行 端口 3306
上,否则您必须始终提及端口,例如您的连接参数应该类似于
"jdbc:mysql://localhost:1234/bd_ds", "root", ""
其中 1234
是端口号。
您还应该执行以下操作之一以查看错误消息:
- 将
e.printStackTrace()
放入 catch
块中。
- 只需删除
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);
最后,确保关闭 PreparedStatement
和 ResultSet
。为了让它自动完成,您可以使用 try-with-resources.
为了简短起见,下一个代码
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()”应该return“真”
我已经打开 XAMPP、apache 和“mysql”
我有驱动连接器
当然还有数据库
除非您的 MySQL 服务器在 运行 端口 3306
上,否则您必须始终提及端口,例如您的连接参数应该类似于
"jdbc:mysql://localhost:1234/bd_ds", "root", ""
其中 1234
是端口号。
您还应该执行以下操作之一以查看错误消息:
- 将
e.printStackTrace()
放入catch
块中。 - 只需删除
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);
最后,确保关闭 PreparedStatement
和 ResultSet
。为了让它自动完成,您可以使用 try-with-resources.