JDBC中SQL查询语句引号使用
jdbc操作数据库来进行模拟用户登入时,可以使用以下方法。
String uname=“张三”;
String pwd=“123”;
String sql = "select * from users where username=’ “+uname+” ’ and password=’ “+pwd+” ’ ";
等价于:String sql = “select * from users where username= “ 张三 ” and password=“123” ”;
注意:最外面单引号里面双引号。
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名");
String uname = scanner.next();
System.out.println("请输入密码");
String pwd = scanner.next();
//连接
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user
useUnicode=true&characterEncoding=utf-8&useSSL=false","root","123456");
//执行sql
Statement smt = connection.createStatement();
String sql = "select * from users where username=' "+uname+" ' and password=' "+pwd+" ' ";
ResultSet rs = smt.executeQuery(sql);
if (rs.next()){
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
//关闭资源
connection.close();
rs.close();
smt.close();
}