栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

DBUtils封装

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

DBUtils封装

DBUtils封装
  • 原理
  • 代码
  • 结果
  • 数据库

原理
  1. 将建立连接和关闭连接的过程封装在DBUtils工具类里
  2. 常规statement无法进行人机交互 无法键盘交互 引入preparestatement
代码

DBUtils类

package com.tyut.common;

import java.sql.*;

public class DBUtils {


    public static Connection getConnection() throws SQLException { //注意static 否则不能用类名调用
        String url="jdbc:mysql://localhost:3306/test01";
        String username="root";
        String userpwd="123456";

        try{
            Connection conn = DriverManager.getConnection(url,username,userpwd);
            return  conn;
        }catch(SQLException e){
            e.printStackTrace();
        }

        return null;

    }

    
    public static void close(ResultSet rs, Statement st, Connection conn){
        try{
            if(rs!=null)
                rs.close();
            if(st!=null)
                 st.close();
            if(conn!=null)
                 conn.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

JDBCDemo_Login_PrepareStatement类

package com.tyut.demo_jdbc;

import com.tyut.common.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCDemo_Login_PrepareStatement {
    public static void main(String[] args) throws Exception {
        //常规statement无法进行人机交互 无法键盘交互 引入preparestatement
        
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username=sc.nextLine();
        System.out.println("请输入密码:");
        String password=sc.nextLine();

        
        Connection conn= DBUtils.getConnection();

        String sql="select * from user where username=? and password=?";//注意 是? 底下通过函数setObject()给?传参数

        PreparedStatement pst=null; //创建preparedstatement对象 通过preparedstatement对象执行语句
        ResultSet rs=null; //结果集
        try{
            pst=conn.prepareStatement(sql);
            pst.setObject(1,username);//第一个参数传username
            pst.setObject(2,password);//第二个参数传password
            rs = pst.executeQuery();
            
            if(rs.next()){
                System.out.println("登陆成功");
                System.out.println("用户名:"+rs.getString("username"));
               System.out.println("密码:"+rs.getString("password"));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            //关闭结果集ResultSet,Preparedment,Connection
            DBUtils.close(rs,pst,conn);
            //关闭Scanner
            sc.close();
        }


    }
}

结果

数据库

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/301808.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号