标签:tst 不用 操作 can 输入密码 getc bcd ring var
例如:
String sql = "select * from user where username=‘" + username + "‘ and password =‘" + password + "‘ ";
执行的时候自动就把变量转换为字符串类型,“”表示字符串,‘’是SQL的字符串和字符
两个双引号和变量拼接在一起,会吧变量转化为字符串
执行SQL的时候是这样的select * from user where username=‘‘ and password =‘‘;
步骤:
1.创建数据库表
CREATE TABLE user( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32), PASSWORD VARCHAR(32) );
2.插入条记录
INSERT INTO user VALUES(null,‘zhangsan‘,‘123‘) INSERT INTO user VALUES(null,‘lisi‘,‘234‘)
package cn.itcast.jdbc; import cn.itcast.util.JDBCUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class JdbcDemo10 { public static void main(String[] args) { //1.键盘录入,接收用户名和密码 Scanner sc = new Scanner(System.in); System.out.println("请输入用户名"); String username = sc.nextLine(); System.out.println("请输入密码"); String password = sc.nextLine(); //2.调用方法login,因为不是静态方法,所以要创建对象 boolean flag = new JdbcDemo10().login(username, password); //3.判断结果,输出同语句 if (flag){ System.out.println("登录成功"); }else { System.out.println("登录失败,用户名或密码错误"); } } /** * 登录方法 */ public boolean login(String username, String password) { if (username == null || password == null) {//如果有一个为空就不用去连接数据库,做操作 return false; } //连接数据库是否判断成功 Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //1.获取数据库连接 conn = JDBCUtils.getConnection(); //2.定义SQL-------------------------------------拼接--------------------------------------------------- String sql = "select * from user where username=‘" + username + "‘ and password =‘" + password + "‘ "; //3.获取执行SQL的对象 stmt = conn.createStatement(); //4.执行查询 rs = stmt.executeQuery(sql); //5.判断 /* if (rs.next()){//不用这样写rs.next()返回的就是true,false return true; }else { return false; }*/ return rs.next();//如果有下一行返回true } catch (SQLException e) { e.printStackTrace(); } finally {//释放资源 JDBCUtils.close(rs, stmt, conn); } return false; } }
标签:tst 不用 操作 can 输入密码 getc bcd ring var
原文地址:https://www.cnblogs.com/rijiyuelei/p/12376753.html