JDBC修仙之路

  1. 加载驱动

准备一个电话

  1. 获取连接

拨号(拨一个号码准确定位到别人)

  1. 准备处理快(创建会话)

准备开始说话

  1. 准备并发送sql语句

开始说话

  1. 获取并处理结果

别人给的回馈

  1. 关闭数据库资源

结束电话

//JDBC步骤

//1.加载驱动(选择数据库)   选择快递公司

//2.获取连接(看看能不能和数据库连接上) 与快递公司建立联系(电话号码 唯一信息)

//3.准备处理快(待会儿用来发送数据)   某个快递员

//4.准备sql语句    将要寄的东西打包

//5.发送sql语句    快递员和东西上路

//6.获取结果集,处理结果集    得到结果,人家已收到你寄的快递

//7.关闭资源(后打开的先关闭)   交易成功

例:

package com.shsxt.JDBC03;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class JDBC006 {
    public static void main(String[] args) {
        Connection conn=null;
        Statement state=null;
        ResultSet rs=null;
        try {
            //从键盘录入账号密码
            Scanner sc=new Scanner(System.in);
            System.out.println("账号:");
            String name=sc.next();
            System.out.println("密码:");
            String pwd=sc.next();
            //1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.获取数据库连接
            conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","SCOTT","TIGER");
            //3.准备处理快和sql语句
            state=conn.createStatement();
            String sql="select * from t_user where username='"+name+"' and password='"+pwd+"'";
            //String sql="select * from t_user where username='明哥' and password='123456'";
            System.out.println("sql=======>"+sql);
            //4.发送sql
            rs=state.executeQuery(sql);
            //5.获取结果集并处理
            //要判断rs的结果是否为空,只要使用一次rs.next方法就行了,如果它返回为false,则证明rs的结果为null
            if(rs.next()){
                System.out.println("欢迎您登陆成功!!!");
            }else{
                System.out.println("登陆失败...");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(state!=null){
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/greyrhinoceros-1998/p/10882444.html