• MySQL第三天


    //连接数据库的工具类
    public class JDBCUtils {

    private static final String USER="root";
    private static final String PWD="root";
    private static final String URL="jdbc:mysql://localhost:3306/girl";
    private static final String DRIVER="com.mysql.jdbc.Driver";
    //1.注册驱动
    static {
    try {
    Class.forName(DRIVER);
    } catch (Exception e){
    e.printStackTrace();
    }
    }
    //2.得到数据库连接
    public static Connection getConnetion() throws SQLException{
    return (Connection) DriverManager.getConnection(URL,USER,PWD);
    }
    //3.关闭资源
    public static void close(Connection con, Statement stat){
    if(stat!=null){
    try {
    stat.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    if(con!=null){
    try {
    con.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    public static void close(Connection con, Statement stat,ResultSet rs){
    if (rs!=null){
    try {
    rs.close();
    }catch (Exception e){
    e.printStackTrace();
    }
    }
    if(stat!=null){
    try {
    stat.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    if(con!=null){
    try {
    con.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    //登陆实现
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入用户名");
    String name= sc.nextLine();
    System.out.println("请输入密码");
    String password=sc.nextLine();
    login(name,password);
    }
    //1.写一个登陆方法
    public static void login(String name,String password){
    Connection con = null;
    Statement stat= null;
    ResultSet rs= null;
    try {
    //1.通过工具类获得链接
    con= JDBCUtils.getConnetion();
    //2.定义sql
    String sql ="select*from yang where ename='"+name+"'and mgr ='"+password+"'";
    //3.获取执行对象
    stat=con.createStatement();
    System.out.println(sql);
    //4.查询数据库 如果有记录 表示登录成功 否则登录失败
    rs=stat.executeQuery(sql);
    if (rs.next()){
    System.out.println("登陆成功");
    }else {
    System.out.println("登陆失败");
    }
    } catch (Exception e){
    e.printStackTrace();
    }finally {
    JDBCUtils.close(con,stat,rs);
    }
    }
     
  • 相关阅读:
    JavaScript没有块级作用域
    JavaScript数据类型
    接口
    Linux用户与组别的操作
    解决 macOS 下 SSH 空闲一段时间后自动断开
    Excel 系列一 之 账户类长数字打开不截断与完全显示
    怎样花两年时间去面试一个人
    北京大学硕士学位论文模板
    Mysql: 图解 inner join、left join、right join、full outer join、union、union all的区别
    刷 LeetCode 时再学习 Python 中引用
  • 原文地址:https://www.cnblogs.com/Y-mmeng/p/10673077.html
Copyright © 2020-2023  润新知