Java调用SQL Server存储过程的步骤如下:
1.首先,要在Java中连接数据库
这里使用JDBC连接SQL Server数据库,示例代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectSQLServer {
// 数据库连接参数
private static final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=TestDB";
private static final String userName = "sa";
private static final String userPwd = "123456";
public static void main(String[] args) {
Connection connection = null;
try {
// 加载驱动程序
Class.forName(driverName);
// 获取连接对象
connection = DriverManager.getConnection(dbURL, userName, userPwd);
// 执行操作
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2.创建Store Procedure
在SQL Server中创建好要调用的存储过程,示例如下:
CREATE PROCEDURE dbo.get_product
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM Product;
END
3.在Java中调用Store Procedure
可以通过Java的PreparedStatement来调用Store Procedure,示例代码如下:
public class CallSQLServerProcedure {
private static final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=TestDB";
private static final String userName = "sa";
private static final String userPwd = "123456";
public static void main(String[] args) {
Connection connection = null;
CallableStatement call = null;
try {
// 加载驱动程序
Class.forName(driverName);
// 获取连接对象
connection = DriverManager.getConnection(dbURL, userName, userPwd);
// 调用存储过程
String sql = "{call dbo.get_product()}";
call = connection.prepareCall(sql);
// 处理结果集
ResultSet rs = call.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("Name") + ", " + rs.getString("Price"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (call != null) {
call.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
以上就是Java中调用SQL Server存储过程的完整攻略,如果你需要调用存储过程并传递参数,可以使用带参数的PreparedStatement来替代上述示例中的CallableStatement。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java中调用SQL Server存储过程详解 - Python技术站