划水的第二天

任务

JDBC的学习

今天的学习任务是在java中对数据库进行操作,数据库在java中书写有7个步骤,步骤事例如下:

   //1.加载驱动
    Class.forName("com.mysql.jdbc.Driver");
    //2.创建连接
    Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&characterEncoding=utf-8&user=root&password=123");
    System.out.println("aaa");fc
    //3.写sql
    String sql="select * from userinfo";
    //4.得到statement对象执行sql
    PreparedStatement statement =connection.prepareStatement(sql);
    //5.得到结果集
    ResultSet rs=statement.executeQuery();
    //6.处理结果集
    while(rs.next()){
        System.out.println(rs.getInt(1));
        System.out.println(rs.getString(2));
        System.out.println(rs.getString(3));
    }
    //7.关闭资源
    rs.close();
    connection.close();
    statement.close();

需要注意的点有:异常地抛出,这里的写法较为随意,最好是用try-catch,将问题具体的抛出分析。
上面是最基本的操作,但是在实际运用中要进行封装
比如将链接数据库和关闭资源封装起来

public class DBUtil {
    public  static Connection getConnection(){
        Connection connection=null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
           connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&characterEncoding=utf-8&user=root&password=123");

        }catch (Exception e){

        }return connection;
    }
    public static void close(Connection connection, PreparedStatement statement, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    }

还有实体类的成分:
划水的第二天_第1张图片

public class UserInfo {
    public int id;
    public String username;
    public String password;
    public UserInfo(){

    }
    public int getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

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

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

你可能感兴趣的:(宁波)