데이터베이스jdbc_메모리 프로세스 호출 + 자동 생성 키 가져오기

자동 생성 키 가져오기
package cn.itcast.demo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.Test;
import cn.itcast.utils.JdbcUtils;
public class demo4 {
   /*
             ,        !
          :        ,        ,
             id,           !
    mysql -uroot -proot
    set character_set_client=gb2312;
   set character_set_results=gb2312;
    use day15;
    create table test(
    id int primary key auto_increment,
    name varchar(40) not null
    )character set utf8 collate utf8_general_ci;
    show tables;
    */
   @Test
   public void getGeneratedKeys(){
      //SQL      (sql_u)
      Connection conn = null;
      PreparedStatement st = null;
      ResultSet rs = null;
      try {
         conn = JdbcUtils.getConnection();
         String sql = "insert into test(name) values(?)";
         st = conn.prepareStatement(sql);
         st.setString(1, "   ");
         st.executeUpdate();
         //    :
         rs=st.getGeneratedKeys();
         if (rs.next()) {
            //       ,      !?      id  !
            System.out.println(rs.getInt("id"));
         }
         
      } catch (Exception e) {
         throw new RuntimeException(e);
      } finally {
         JdbcUtils.release(conn, st, rs);
      }
   }
}

메모리 프로세스 호출
package cn.itcast.demo;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import org.junit.Test;
import cn.itcast.exception.DaoException;
import cn.itcast.utils.JdbcUtils;
public class demo5 {
   /*
          
              !        ,      hibernate
          oracle       !
    1, mysql          (     )!
                   'pre_eminent:'   
    delimiter ^
    create procedure demo5(IN inputParam VARCHAR(255),INOUT inoutParam VARCHAR(255))
    BEGIN
          SELECT CONCAT('pre_eminent:',inputParam) into inoutParam;
    END^
    delimiter ;
    2,drop procedure demo5      */
   @Test
   public void sqlProcedure(){
      //SQL          (sql_procedure)
      Connection conn = null;
      CallableStatement st = null;
      ResultSet rs = null;
      try {
         conn = JdbcUtils.getConnection();
         /*            demo5          (     )!
          * call SQL   !       !
          *  1      , 2      !*/
         String sql = "{call demo5(?,?)}";
         st = conn.prepareCall(sql);
         //              !   2  sqlType
         st.setString(1, "nice to meet you!");
         //       ,   java.sql.Types   !
         st.registerOutParameter(2, Types.VARCHAR);
         //       sql  
         st.execute();
         //     2  ,     inoutParam  !
         System.out.println(st.getString(2));
      } catch (Exception e) {
         throw new DaoException(e);
      } finally {
         JdbcUtils.release(conn, st, rs);
      }
   }
}

좋은 웹페이지 즐겨찾기