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);
    }
    }
     
  • 相关阅读:
    html优化
    HTML练习(网页计算器)
    hdu--4574 Bombs(dfs)
    Robots at Warehouse(搜索+vector的使用)
    poj 2111 Millenium Leapcow(记忆化搜索)
    Codeforces Round #408 (Div. 2) C. Bank Hacking(暴力啊!暴力)
    Gym
    Gym
    浙江省赛--D
    浙江省赛--C
  • 原文地址:https://www.cnblogs.com/Y-mmeng/p/10673077.html
Copyright © 2011-2022 走看看