标签:java 存储过程
在其他地方我已经写过一个mySql存储过程的简单实现http://jianboli.blog.51cto.com/12075002/1884019
这里是java调用存储过程。
package com.lijianbo.procedure;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
/**
* @author
* 存储过程MySQL
*/
public class ProcedureMySql {
public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/test";
public static final String USERNAME = "root";
public static final String PASSWORD = "root";
public static void main(String[] args) throws Exception {
// test1();
// test2();
testIdAdd();
}
public static void test1() throws Exception
{
Class.forName(DRIVER_CLASS);
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
String sql = "{CALL test1(?)}"; //调用存储过程
CallableStatement cstm = connection.prepareCall(sql); //实例化对象cstm
cstm.setString(1, "李"); //存储过程输入参数
cstm.execute(); // 执行存储过程
cstm.close();
connection.close();
}
/**
* 查询总的价格
* getTotalByUser2
* call getTotalByUser2(1, true, @total); -- 加税
*select @total;
* @throws Exception
*/
public static void test2() throws Exception {
Class.forName(DRIVER_CLASS);
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
String sql = "{CALL getTotalByUser2(?,?,?)}"; //调用存储过程
CallableStatement cstm = connection.prepareCall(sql); //实例化对象cstm
cstm.setInt(1, 1); //设置第一个传入参数
cstm.setBoolean(2, true); //设置第二个传入参数
cstm.registerOutParameter(3, Types.DECIMAL); // 设置返回值类型 即返回值
cstm.execute(); // 执行存储过程
System.out.println(cstm.getString(3));
cstm.close();
connection.close();
}
/**
*id自增
* getTotalByUser2
* call getTotalByUser2(1, true, @total); -- 加税
*select @total;
* @throws Exception
*/
public static void testIdAdd() throws Exception {
Class.forName(DRIVER_CLASS);
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
String sql = "{CALL test1(?)}"; //调用存储过程
CallableStatement cstm = connection.prepareCall(sql); //实例化对象cstm
cstm.setString(1, "测试"); //设置第一个传入参数
cstm.execute(); // 执行存储过程
cstm.close();
connection.close();
}
}存储过程既可以在java中调用,也可以在触发器中调用,欲知简单实现。可以参考我的上一篇文章“触发器的简单实现”。
http://jianboli.blog.51cto.com/12075002/1884180
我这里只是一个示例,你可以参考里面的注释,具体存储过程的名字要根据你自己写的来修改。
时间:2016年12月20日16:59:13
本文出自 “JianBo” 博客,请务必保留此出处http://jianboli.blog.51cto.com/12075002/1884370
标签:java 存储过程
原文地址:http://jianboli.blog.51cto.com/12075002/1884370