zoukankan      html  css  js  c++  java
  • java JDBC自我总结

    preparedstatement和statement的区别

    当不需要预编译时(不需要占位符)可以选用statement,存在不安全

    当有占位符(?)时,需要选用preparedstatement

    select 查询语句,选用executeQuery()方法

    执行后返回代表查询结果的ResultSet对象

    ResultSet rs =pst.executeQuery("select * from teacher");  

    while (rs.next()){  

                System.out.println(rs.getInt(1) + "/t" +    rs.getString(2));   

     INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。选用executeUpdate()方法

    executeUpdate 的返回值是一个整数(int),指示受影响的行数(即更新计数)。
    对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零

    insert实例

    private static int insert(Student student) {
        Connection conn = getConn();
        int i = 0;
        String sql = "insert into students (Name,Sex,Age) values(?,?,?)";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            pstmt.setString(1, student.getName());
            pstmt.setString(2, student.getSex());
            pstmt.setString(3, student.getAge());
            i = pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    查询样例

    private static Integer getAll() {
        Connection conn = getConn();
        String sql = "select * from students";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            int col = rs.getMetaData().getColumnCount();
            System.out.println("============================");
            while (rs.next()) {
                for (int i = 1; i <= col; i++) {
                    System.out.print(rs.getString(i) + "	");
                    if ((i == 2) && (rs.getString(i).length() < 8)) {
                        System.out.print("	");
                    }
                 }
                System.out.println("");
            }
                System.out.println("============================");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
  • 相关阅读:
    zombie处理
    exec
    fork
    udp program
    PS中进程状态
    关闭socket连接最好的方法
    setsockopt
    【Python】Webpy 源码学习
    web.py 安装
    WSGI、flup、fastcgi、web.py的关系
  • 原文地址:https://www.cnblogs.com/dk2557/p/10869991.html
Copyright © 2011-2022 走看看