JDBC练习一(基础)

113 阅读3分钟

简单(DDL和DML)

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo2 {
    public static void main(String[] args) {
        Statement stmt=null;
        Connection conn=null;
        try {
//           1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
//         3.定义SQL
            String sql="delete from emp where name='小旋风'";
//            这里可以执行DDL和DML语言
            try {
//                2.获取连接对象
                conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/study","root","123456");
//              4.  获取执行SQL对象
                stmt=conn.createStatement();
//                5.执行SQL
                int count=stmt.executeUpdate(sql);
//                6.处理结果
                System.out.println(count);
                if(count>0){
                    System.out.println("添加成功");
                }else{
                    System.out.println("添加失败");
                }

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
//            7.释放资源
//            stmt.close();
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}



封装多个结果(利用游标)

  1. ResultSet:结果集对象,封装查询结果
  • next():游标向下移动一行

  • getxx():获取数据

    • xx:代表数据类型 如:int getInt(),String getString()
    • 参数:
      • int:代表列的编号,从1开始 如:getString(1)
      • String:代表列的名称。 如:getDouble("balance")
  • 注意:

    • 实验步骤:
      • 游标向下移动一步
      • 判断是否有数据
      • 获取数据

boolean next():游标向下移动一行,判断当前是否是最后一行末尾,如果是,则返回false,如果不是,则返回true
循环判断游标是否是最后一行末尾

             while(rs.next()){
              int id= rs.getInt("id");
             String name= rs.getString("name");
               int age=rs.getInt(3);
               String job=rs.getString(4);
               Date data=rs.getDate(6);
               System.out.println(id+"---"+name+"---"+age+"---"+job+"---"+data);
               }

package jdbc;

import java.sql.*;

public class JDBCDemo3 {
    public static void main(String[] args) {
        Statement stmt=null;
        Connection conn=null;
        ResultSet rs=null;
        try {
//           1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
//         3.定义SQL
            String sql="select * from emp ";
            try {
//                2.获取连接对象
                conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/study","root","123456");
//              4.  获取执行SQL对象
                stmt=conn.createStatement();
//                5.执行SQL
                 rs=stmt.executeQuery(sql);
//                6.处理结果
//                6.1 让游标向下移动一行

                while(rs.next()){
//                    循环判断游标是否是最后一行末尾

//                6.2 获取数据
               int id= rs.getInt("id");
              String name= rs.getString("name");
                int age=rs.getInt(3);
                String job=rs.getString(4);
                Date data=rs.getDate(6);
                System.out.println(id+"---"+name+"---"+age+"---"+job+"---"+data);
                }

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
//            7.释放资源
//            stmt.close();
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

结果如下

联想截图_20221223143906.png




练习

  • 查询emp表的数据将其封装为对象,然后转载集合,返回。
    • 定义Emp类
    • 定义方法public List findAll(){}
    • 实现方法 select * from emp;
package jdbc.cn;

import java.util.Date;

/*
* 封装Emp表数据的JavaBean
* */
public class Emp {
    private int id;

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", age=" + age +
                ", job='" + job + ''' +
                ", salary='" + salary + ''' +
                ", joindate=" + joindate +
                '}';
    }

    private  String name;

    public Date getJoindate() {
        return joindate;
    }

    public void setJoindate(Date joindate) {
        this.joindate = joindate;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    private int age;
    private String job;

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    private int salary;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private Date joindate;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
package jdbc;

import jdbc.cn.Emp;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/*
* 查询所有emp对象
* */
public class JDBCDemo4 {
    public static void main(String[] args) {
        List<Emp> list=new JDBCDemo4().findAll();
        System.out.println(list);
        System.out.println(list.size());
    }

    public List<Emp> findAll(){
        Connection conn=null;
        ResultSet rs=null;
        Statement stmt=null;
        List <Emp> list=null;

//        1.注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
//            2.获取连接

            try {
                 conn = DriverManager.getConnection("jdbc:mysql:///study","root","123456");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
//                3.定义SQL
            String sql="select * from emp ";
//                4. 获取执行SQL的对象
            try {
                stmt=conn.createStatement();
//                5. 执行SQL
                rs=stmt.executeQuery(sql);
//                6. 遍历结果集,封装对象,装载集合
                Emp emp=null;
                 list=new ArrayList<Emp>();
                while (rs.next()){
//                    7.获取数据
                    int id=rs.getInt("id");
                    String name=rs.getString("name");
                    int age=rs.getInt("age");
                    String job=rs.getString("job");
                    int salary =rs.getInt("salary");
                    Date joindate=rs.getDate("entrydate");

//                    创建emp对象,并赋值
                    emp=new Emp();
                    emp.setId(id);
                    emp.setAge(age);
                    emp.setName(name);
                    emp.setJob(job);
                    emp.setJoindate(joindate);
                    emp.setSalary(salary);

//                    装载集合
                    list.add(emp);
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return list;
    }

}