java数据库编程(6) 使用存储过程

  1. 可以使用下面这样的sql语句创建一个存储过程
    mysql> delimiter //
    mysql> create procedure PTest(a int, b int, out sum int)
        -> begin
        -> set sum = a + b;
        -> end;
        -> //
  2. 在java中调用存储过程使用的是CallableStatement,它是通过Connection的preparedCall()方法来创建的,它在创建的时候需要传入调用的的sql语句。

  3. CallableStatement调用sql语句的时候有固定的格式,{call 过程名(?,?,?...)}这些问号是作为参数在下文中传入的。

  4. 具体的讲解穿插在代码中

    import javafx.animation.KeyValue;
    
    import java.io.FileInputStream;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Types;
    import java.util.Properties;
    
    public class CallableStatementTest {
        
    //    这些都是常规操作了,就不讲解了。
        private String driver;
        private String url;
        private String user;
        private String pass;
    
        public void initParam(String paramFile) throws Exception{
            Properties properties = new Properties();
            properties.load(new FileInputStream(paramFile));
            driver =  properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            pass = properties.getProperty("pass");
        }
    
        public void callProcedure() throws Exception{
            Class.forName(driver);
            try(
                    Connection connection  = DriverManager.getConnection(url, user, pass);
                    
                    CallableStatement cstmt = connection.prepareCall("{call PTest(?, ?, ?)}"))
    //                这一句就是创建CallableStatement对象了,在创建的时候就传入了对应的sql语句,意思是调用一个名字为
    //                PTest,具有三个参数的存储过程。
                    
            {
    //            这里就是设置参数了,将第一个参数设置为4,第二个参数设置为5
                cstmt.setInt(1,4);
                cstmt.setInt(2,5);
                
                cstmt.registerOutParameter(3, Types.INTEGER);
    //            这一句的意思是注册第三个参数的类型是int
                
                cstmt.execute();
    //            执行存储过程
                
                System.out.println("执行结果是" + cstmt.getInt(3));
    //            这一句是得到第三个参数,其类型为int
            }
        }
    
        public static void main(String args[]) throws  Exception{
            CallableStatementTest ct = new CallableStatementTest();
            ct.initParam("mysql.ini");
            ct.callProcedure();
        }
    }
    //运行程序,得到以下输出
    //    执行结果是9

猜你喜欢

转载自blog.csdn.net/weixin_39452731/article/details/83035661
今日推荐