第二季--Statement

    技术2022-05-19  22

    一、提问如何进行代码复用   继承复用、组合复用   私有复用:一个方法在一个类的内部使用   工具方法:使用静态方法,使用类名直接调用                                       二、Statement  execute(sql); 当不知道执行的SQL语句是什么类型的时候执行 ,返回值是booleanexecuteQuery(sql); 执行查询语句executeUpdate(sql); 执行更新语句

    三、PreparedStatement可以使用参数替代sql语句中的某些参数使用 "?"代替,他先将带参数的sql语句发送到数据库,进行编译,然后PreparedStatement会将参数发送给数据库。在使用PreparedStatement时,在设置相应参数时,要指明参数的位置和类型,以及给出参数值根据不同的参数类型使用不同的setXXX(参数的位置,参数值)来设置参数

    例:public void insert(Student s){        Connection con=ConnectionFactory.getConnection();//建立连接        String sql="insert into student(id,name) values(?,?)";        PreparedStatement ps=null;        try {            ps=con.prepareStatement(sql);//创建一个PreparedStatement      int index=1;            ps.setInt(index++,s.getStuId());  //为参数赋值            ps.setString(index++,s.getName());            ps.executeUpdate();        } catch (SQLException e) {            e.printStackTrace();        }finally{            if(ps!=null)                try {                    ps.close();                } catch (SQLException e) {                    e.printStackTrace();                }                if(con!=null)                    try {                        con.close();                    } catch (SQLException e) {                        e.printStackTrace();                    }        }    }

    CallableStatement是可以用非sql语句来访问数据库,他是通过调用存储过程(PL/SQL)来访问数据库的。可以直接使用连接来调用 prepareCall(...)方法,来执行这个存储过程,"..."是存储过程的名字。

    对于系统时间要去数据库时间TimeStamp 和 Date都可以保存时间TimeStamp可以保存时、分、秒的数据,Date只保存日期年月的信息。

    SQLException是检查异常必须处理要么throws ,要么try{}catch(){}getErrorCode()可以获得错误码,可以对错误进行查询。

    四、源数据JDBC中有两种源数据,一种是数据库源数据,另一种是ResultSet源数据。

    源数据就是描述存储用户数据的容器的数据结构。

    ResultSet rs=ps.executeQuery(sql);ResultSetMetaData m=rs.getMetaData();

    getColumnCount(),获得实际列数getColumnName(int colnum),获得指定列的列名getColumnType(int colnum),获得指定列的数据类型getColumnTypeName(int colnum),获得指定列的数据类型名

    //打印结果集public static void printRS(ResultSet rs)throws SQLException{    ResultSetMetaData rsmd = rs.getMetaData();    while(rs.next()){       for(int i = 1 ; i < = rsmd.getColumnCount() ; i++){          String colName = rsmd.getColumnName(i);          String colValue = rs.getString(i);          if(i>1){             System.out.print(",");          }          System.out.print(name+"="+value);       }       System.out.println();    }}


    最新回复(0)