在使用Java开发时,经常会遇到调用Sql Server存储过程的问题,接下来的SQL server内容就为您示例介绍Java调用Sql Server存储过程的实现过程,希望可以帮助您解决Java调用Sql Server存储过程的难题。
1.数据库连接
package com.hujuan.conn; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConn { public static Connection getConnection(){ String className= "com.microsoft.jdbc.sqlserver.SQLServerDriver"; String url = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=login"; String name = "sa"; String password = "sasa"; try { Class.forName(className); return DriverManager.getConnection(url,name,password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; } }
2.通过连接调用存储过程
package com.hujuan.dao; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import com.hujuan.conn.DatabaseConn; public class SqlServerProc { public static void main(String[] args) { Connection conn = null; CallableStatement call = null; conn = DatabaseConn.getConnection(); try { call = conn.prepareCall("{call insertUserinfo( , , , )}"); call.setString(1, "hujuan"); call.setString(2, "女"); call.setString(3, "1985-06-16"); call.registerOutParameter(4, Types.INTEGER); call.executeUpdate(); int value = call.getInt(4); System.out.println(value); } catch (SQLException e) { e.printStackTrace(); }finally{ try { if(call != null)call.close(); if(conn != null)conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
返回结果集
package com.hujuan.dao; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import com.hujuan.conn.DatabaseConn; public class SqlServerProc { public static void main(String[] args) {Connection conn = null; CallableStatement call = null; ResultSet rs = null; conn = DatabaseConn.getConnection(); try { call = conn.prepareCall("{ =call selectUserinfo()}"); call.registerOutParameter(1, Types.REAL); rs = call.executeQuery(); while(rs.next()){ System.out.println(rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); }finally{ try { if(rs != null)rs.close(); if(call != null)call.close(); if(conn != null)conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }