JAVA中捕获SQL中存储过程的异常信息(2007-05-19 20:41:46)转载▼ 分类: Java编程
//在java中捕获sql存储过程中的异常
//java代码:
package sqlexceptiontest;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.SQLServerException;
public class SqlException{
Connection conn = null;
Statement stmt = null; //执行SQL语句的对象
ResultSet rs = null;
public SqlException() {
String jdbcDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String jdbcUrl = "jdbc:sqlserver://localhost:1433;database=zhang";
String jdbcUser = "sa";
String jdbcPwd = "123";
try {
Class.forName(jdbcDriver);
conn=DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);
java.sql.CallableStatement call=conn.prepareCall("{call excep(?,?,?)}");
call.setInt(1,1);
call.setInt(2,0);
call.registerOutParameter(3,java.sql.Types.VARCHAR);
call.execute();
System.out.println(call.getString(3));
}
catch(SQLServerException e) {
e.printStackTrace();
}
catch (ClassNotFoundException ex)
{
}
catch (SQLException ex)
{
}
}
public static void main(String[] args)
{
SqlException db=new SqlException();
}
}
=====================
SQL代码
create database zhang
go
use zhang
go
create proc excep
@beichushu int,
@chushu int,
@error varchar(max) output
as
begin try
declare @shang int
set @shang=@beichushu/@chushu
print @shang
end try
begin catch
set @error='错误信息'+ERROR_MESSAGE()
end catch
drop proc excep
declare @error varchar(max)
exec excep 5,0,@error output
print @error
分享: 分享到新浪Qing
//在java中捕获sql存储过程中的异常
//java代码:
package sqlexceptiontest;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.SQLServerException;
public class SqlException{
Connection conn = null;
Statement stmt = null; //执行SQL语句的对象
ResultSet rs = null;
public SqlException() {
String jdbcDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String jdbcUrl = "jdbc:sqlserver://localhost:1433;database=zhang";
String jdbcUser = "sa";
String jdbcPwd = "123";
try {
Class.forName(jdbcDriver);
conn=DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);
java.sql.CallableStatement call=conn.prepareCall("{call excep(?,?,?)}");
call.setInt(1,1);
call.setInt(2,0);
call.registerOutParameter(3,java.sql.Types.VARCHAR);
call.execute();
System.out.println(call.getString(3));
}
catch(SQLServerException e) {
e.printStackTrace();
}
catch (ClassNotFoundException ex)
{
}
catch (SQLException ex)
{
}
}
public static void main(String[] args)
{
SqlException db=new SqlException();
}
}
=====================
SQL代码
create database zhang
go
use zhang
go
create proc excep
@beichushu int,
@chushu int,
@error varchar(max) output
as
begin try
declare @shang int
set @shang=@beichushu/@chushu
print @shang
end try
begin catch
set @error='错误信息'+ERROR_MESSAGE()
end catch
drop proc excep
declare @error varchar(max)
exec excep 5,0,@error output
print @error
分享: 分享到新浪Qing