Statement、PreparedStatemnt、CallableStatement

第一、Statement(Statement代表一个特定的容器,来对一个特定的数据库执行语句)


* 执行查询的方法

Statement=Connection.createStatement();//创建执行sql的句柄对象
ResultSet=Statement.executeQuery(sql);//执行查询,返回结果集

* 执行增删改的方法

Statement=Connection.createStatement();//创建执行sql的句柄对象

int t=Statement.executeUpdate(sql);//执行插入,返回的是影响的行数
  
}


第二、PreparedStatemnt(PreparedStatemnt用于执行预编译的SQL语句。)


*执行预编译的查询方法
           
   String sql="select * from student where sage>? and sname like ?";
    PreparedStatemnt=Connection.prepareStatement(sql);//把sql语句发送到数据库中,执行预编译

    PreparedStatemnt.setInt(1, 第一个?号的值);
    PreparedStatemnt.setString(2, 第二个?号的值);
    ResultSet=PreparedStatemnt.executeQuery();//执行查询,返回结果集

*执行预编译插入方法

   String sql="insert into student values(?,?,?,?)";
    PreparedStatemnt=Connection.prepareStatement(sql);//把预编译的sql语句发送到数据库中,执行预编译
    PreparedStatemnt.setString(1, 第一个?的值);
    PreparedStatemnt.setInt(2, 第二个?的值);
    PreparedStatemnt.setByte(3, 第三个?的值);
    PreparedStatemnt.setString(4, 第四个?的值);
   
   int count=PreparedStatemnt.executeUpdate();//执行插入,返回的结果为影响的行数
   
第三、CallableStatement(CallableStatement用于执行对一个数据库内嵌过程的调用)

*调用有in参数的存储过程(查询)

  
    CallableStatement=Connection.prepareCall("{call 存储过程名(?)}");//在应用程序里面调用数据库里的存储过程,? 分别对 应存储过程的参数
   CallableStatement.setString(1, in参数的值);
    ResultSet=CallableStatement.executeQuery();//执行查询,获得结果集
   
              
*调用有in参数的存储过程(插入)
    CallableStatement=Connection.prepareCall("{call 存储过程名(?,?,?,?)}");//在应用程序里面调用数据库里的存储过程,? 分别对应存储过程的参数   
    CallableStatement.setString(1, 第一个in参数);
    CallableStatement.setInt(2, 第二个in参数);
    CallableStatement.setByte(3, 第三个in参数);
    CallableStatement.setString(4, 第四个in参数);
   
   int count=CallableStatement.executeUpdate();//执行插入,返回的结果为影响的行数
   

*调用有in、out参数的存储过程
    CallableStatement=Connection.prepareCall("{call 存储过程名(?,?)}");//执行存储过程的查询方法
    CallableStatement.setInt(1, ids);//输入参数
    CallableStatement.registerOutParameter(2, Types.VARCHAR);//注册out参数
    CallableStatement.execute();//执行查询
   
   String name=CallableStatement.getString(2);//输出out参数

原文地址:https://www.cnblogs.com/hoobey/p/7063117.html