1. 어떻게 JDBC 에서 저장 과정 을 호출 합 니까?

6346 단어 면접 문제
  ,JDBC   Statement,CallableStatement   PreparedStatement           ,       SQL       ,           ,  CallableStatement                 。[  Statement     ](http://edu.clouderwork.com/course/373/learn#lesson/1923)

단계:
저장 프로시저 생 성:
mysql> CREATE DATABASE EMP $$

mysql> DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$

mysql> CREATE PROCEDURE `EMP`.`getEmpName`
    ->    (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
    -> BEGIN
    ->    SELECT first INTO EMP_FIRST
    ->    FROM Employees
    ->    WHERE ID = EMP_ID;
    -> END $$
mysql> DELIMITER ;

Callable Statement 대상 을 만 들 고 저장 과정 을 호출 합 니 다. (MySql 데이터 베 이 스 를 사용 합 니 다)
package ProcedureTest;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.dbcp.BasicDataSource;


public class JdbcConnectedPro {
    private static Connection connection=null;
    private static CallableStatement callableStatement = null;
    //private static ResultSet resultSet = null;//   
    private static String sql = null;
    /**
     *   connection  
     * @return
     */
    public static Connection getConnection() {
        //  dataSource
        BasicDataSource dataSource = new BasicDataSource();
        //       
        dataSource.setDriverClassName("org.gjt.mm.mysql.Driver");
        //        
        dataSource.setUrl("jdbc:mysql://localhost:3306/emp");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        try {
            connection=dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    /**
     *          CallableStatement  
     * @return
     */
    public static CallableStatement getStatement() {
        //String sql = "";//{call getEmpName (?, ?)}
        try {
            callableStatement = connection.prepareCall(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return callableStatement;
    }
    //    
    public static void close() {
        if (null != callableStatement) {
            try {
                callableStatement.close();
                if (null != connection) {
                    connection.close();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        sql = "{call getEmpName (?, ?)}";
        try {
            getConnection();
            getStatement();
            callableStatement.setInt(1, 1);
            callableStatement.registerOutParameter(2, Types.VARCHAR);
            callableStatement.execute();//  
            int result = callableStatement.getInt(2);
            System.out.println("     "+result);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

좋은 웹페이지 즐겨찾기