模拟登陆功能,通过名称和地区进行登录
先看一下运行效果:
这是我数据库的数据:
为什么会登录失败呢?
dname和loc字段的输入都是一模一样的
但仔细看我们打印的SQL语句会发现被单引号括起来的字段好像是多了个空格,既然如此我们拿到SQL语句到查询编辑器里面运行看看效果
果不其然,是字符串里面的空格在作怪,我当时在测试的时候也是找了好半天才想起测一下SQL语句,最终发现了问题,好在没有第一次掉入坑里待的时间久了.
以下是全部代码
/*
* Statement对象执行SQL语句时,对SQL进行参数拼接时 因为空格产生的bug演示
*/
public class TestLogin1 {
public static void main(String[] args) throws Exception {
login();
}
/**
* 封装了方法,用来获取数据库的连接
*
* @return
*/
public static Connection getConnection() throws Exception {
Connection connection = null;
//1, 注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2. 获取数据库的连接
//String url ="jdbc:mysql://localhost:3306/mydb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false";
String url = "jdbc:mysql://localhost:3307/cgb2107?useSSL=false";
connection = DriverManager.getConnection(url, "root", "root");
return connection;
}
/*
模拟登陆功能,通过名称和地区进行登录
*/
private static void login() {
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
connection = getConnection();
String name = new Scanner(System.in).nextLine();
String loc = new Scanner(System.in).nextLine();
//3, 定义SQL
String sql = "select * from dept where dname = ' " + name + " 'and loc =' " + loc + " ' ";
System.out.println(sql);
//4,获取传输器
statement = connection.createStatement();
//5, 处理结果集
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6, 释放资源
close(resultSet, statement, connection);
}
}
private static void close(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (resultSet != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (resultSet != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}