zoukankan      html  css  js  c++  java
  • 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);
    }
    }
     
  • 相关阅读:
    构建之法读书笔记 第4章 两人合作
    ASE19 团队项目 alpha 阶段 Frontend 组 scrum9 记录
    ASE —— 第二次结对作业
    ASE —— 第一次结对作业
    高级软件工程 —— 第一周博客作业
    软工个人总结
    六月上团队项目心得
    团队项目心得
    结对编程收获
    结对作业——随机生成四则运算(Core 第7组)
  • 原文地址:https://www.cnblogs.com/Y-mmeng/p/10673077.html
Copyright © 2011-2022 走看看