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);
    }
    }
     
  • 相关阅读:
    C​S​S3​:​transition与visibility
    CSS ::before 和 ::after 伪元素 进阶
    [转]达梦数据库报错:不能同时包含聚集KEY和大字段(text类型)
    [转].netcore webapi post参数长度超过最大限制
    efcore执行sql查询(无需定义dbset<model>)
    Rabbitmq的死信
    用Docker搭建RabbitMq的普通集群和镜像集群
    .NetCore在IdentityServer4因为Cookies的SameSite导致授权登录跳转回登录页的问题
    2021>2022
    js 宽高相关及其应用
  • 原文地址:https://www.cnblogs.com/Y-mmeng/p/10673077.html
Copyright © 2011-2022 走看看