import java.sql.*;
import javax.sql.*;
import javax.naming.*;
......
private int InsertProject(HttpServletRequest request, HttpServletResponse response)
{
int Result = -1;
// 调用存储过程
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
// 连接数据库
Context ctx = new InitialContext();
// 以下两种连接方式根据连接MySQL还是SQLSERVER来决定采用
DataSource ds = (DataSource) ctx.lookup("jdbc/erp"); // SQLSERVER 使用
conn = ds.getConnection();
CallableStatement cs = conn.prepareCall("{ call testProc (?, ?) } "); // 问号个数代表参数个数
// 没参数则不需要写小括号和括号内的问号 ,例如下面的例子
// CallableStatement cs = conn.prepareCall("{ call testProc) } "); // 问号个数代表参数个数
// 设置参数 有两个参数
cs.setString(1, "str1");
cs.setString(2, "str2");
rs = cs.executeQuery();
if (rs.next() == true)
{
String a = rs.getString("f1");
String b = rs.getString("f2");
}
// 创建 JDBC 申明
// stmt = con.createStatement();
// stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); // sql server 下如果存在 last 或者 first 方法则使用 */
// 执行SQL命令
// Result = stmt.executeUpdate(sql);
//
// Result = 1;
}
catch (Exception e)
{
Result = -1;
e.printStackTrace();
}
finally
{
if (rs != null)
{
try
{
rs.close();
}
catch (Exception e)
{
}
}
if (stmt != null)
{
try
{
stmt.close();
}
catch (Exception e)
{
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
return Result;
}
//----------------------------------
存储过程如下
-------------------------------------
CREATE PROCEDURE testProc
-- Add the parameters for the stored procedure here
@val1 varchar(10),
@val2 varchar(10)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
select @val1 as [f1], @val2 as [f2], 'ccc' as [f3]
END
GO
/* 测试存储过程时调用
exec testProc 'name111', 'name222'
*/