最初代码
private static void method() throws Exception {
//1.注册驱动 Driver
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接(用户名 密码 端口号 库名)
String usl = "jdbc:mysql://localhost:3306/cgb2106?characterEncoding=utf8";
Connection c = DriverManager.getConnection(usl, "root", "root");
//3.获取传输器
//Statement s = c.createStatement();
String sql = "select * from user where name = ? and password = ?";
PreparedStatement ps = c.prepareStatement(sql);
//设置参数
System.out.println("请输入用户名");
String a = new Scanner(System.in).nextLine();
System.out.println("请输入密码");
String b = new Scanner(System.in).nextLine();
ps.setString(1,a);
ps.setString(2,b);
//4.执行sql
//String sql = "SELECT * FROM USER WHERE NAME='" + a + "' AND PASSWORD='" + b + "'";
//ResultSet r = s.executeQuery(sql);
ResultSet r = ps.executeQuery();
//处理结果集
if (r.next()) {//next()用来判断有没有数据,查到了返回true
System.out.println("恭喜您,登录成功!");
} else {
System.out.println("用户名或者密码输入错误!");
}
//6.释放资源
r.close();
ps.close();
c.close();
}
Spring的JdbcTemplate