package com.bjpowernode;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class JDBCTest07 {
public static void main(String[] args){
Map<String,String> userLoginInfo = initUI();
boolean loginSuccess=login(userLoginInfo);
System.out.println(loginSuccess ? "登陆成功!" : "登陆失败!");
}
//用户登陆
private static boolean login(Map<String, String> userLoginInfo) {
//JDBC代码
boolean loginSuccess=false;
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
String RoomNumber=userLoginInfo.get("RoomNumber");
String Owner1=userLoginInfo.get("Owner1");
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn=DriverManager.getConnection("jdbc:mysql://rm-bp2o54v31968j69si175310nm.mysql.rds.aliyuncs.com:3306/test_db","root_db","123456");
//3、获取预编译的数库操作对象
String sql="SELECT * FROM tb_owner WHERE RoomNumber= ? AND Owner1= ?";
//这里没有问题啊????
ps=conn.prepareStatement(sql);
ps.setString(1,RoomNumber);
ps.setString(2,Owner1);
//4、执行SLQ
rs=ps.executeQuery();
if(rs.next()){
loginSuccess=true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
private static Map<String, String> initUI() {
Scanner s=new Scanner(System.in);
System.out.print("房号:");
String RoomNumber=s.nextLine();
System.out.print("姓名:");
String Owner1=s.nextLine();
Map<String,String>userLoginInfo=new HashMap<>();
userLoginInfo.put("RoomNumber",RoomNumber);
userLoginInfo.put("Owner1",Owner1);
return userLoginInfo;
}
}
用上面的法就是不行,但用以下方法是没有问题的!
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
conn=DriverManager.getConnection("jdbc:mysql://rm-bp2o54v31968j69si175310nm.mysql.rds.aliyuncs.com:3306/test_db","root_db","123456");
//获取数据库对象
stmt=conn.createStatement();
//执行SL语句
sql = "SELECT * FROM tb_owner WHERE RoomNumber='"+RoomNumber+"' AND Owner1='"+Owner1+"'";
rs=stmt.executeQuery(sql);
//处理结果集
if(rs.next()){
loginSuccess=true;
}
看着应该没啥问题
你可以参考 https://help.aliyun.com/knowledge_detail/41741.html 官方的例子测试下,和驱动版本、依赖包的包是否可能相关
我刚来也是怀疑驱动版本问题,但用以下这种方法是没有问题的!如果驱动有问题,下面应该是有问题了!
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
conn=DriverManager.getConnection("jdbc:mysql://rm-bp2o54v31968j69si175310nm.mysql.rds.aliyuncs.com:3306/test_db","root_db","123456");
//获取数据库对象
stmt=conn.createStatement();
//执行SL语句
sql = "SELECT * FROM tb_owner WHERE RoomNumber='"+RoomNumber+"' AND Owner1='"+Owner1+"'";
rs=stmt.executeQuery(sql);
//处理结果集
if(rs.next()){
loginSuccess=true;
}
@润物之音: 报错的具体信息是啥?这里估计可能有些线索
很明显,你从数据库查询出数据之后,只是给loginSuccess设置了true,但并没有返回,函数返回的都是最后一句话的return false,所以始终会返回false,可以把loginSuccess=true改为return true,或最后一句话改成return loginSuccess;