首頁技術(shù)文章正文

JDBC如何調(diào)用存儲過程

更新時間:2018-01-23 來源:黑馬程序員 瀏覽量:

啥也不說,直接上代碼了!

1. package cn.itcast.zx;

2.

3. import java.sql.CallableStatement;

4.

5. import java.sql.Connection;

6.

7. import java.sql.DriverManager;

8.

9. import java.sql.SQLException;

10.

11. import java.sql.Types;

12.

13.

14. public class JdbcTest {

15.

16.

17. /**

18.

19. * @param args

20.

21. */

22.

23. public static void main(String[] args) {

24.

25. // TODO Auto-generated method stub

26.

27. Connection cn = null;

28.

29. CallableStatement cstmt = null;

30.

31. try {

32.

33. //這里最好不要這么干,因為驅(qū)動名寫死在程序中了

34.

35. Class.forName("com.mysql.jdbc.Driver");

36.

37. //實際項目中,這里應(yīng)用DataSource數(shù)據(jù),如果用框架,

38.

39. //這個數(shù)據(jù)源不需要我們編碼創(chuàng)建,我們只需Datasource ds = context.lookup()

40.

41. //cn = ds.getConnection();

42.

43. cn = DriverManager.getConnection("jdbc:mysql:///test","root","root");

44.

45. cstmt = cn.prepareCall("{call insert_Student(?,?,?)}");

46.

47. cstmt.registerOutParameter(3,Types.INTEGER);

48.

49. cstmt.setString(1, "wangwu");

50.

51. cstmt.setInt(2, 25);

52.

53. cstmt.execute();

54.

55. //get第幾個,不同的數(shù)據(jù)庫不一樣,建議不寫

56.

57. System.out.println(cstmt.getString(3));

58.

59. } catch (Exception e) {

60.

61. // TODO Auto-generated catch block

62.

63. e.printStackTrace();

64.

65. }

66.

67. finally

68.

69. {

70.

71.

72.

73. /*try{cstmt.close();}catch(Exception e){}

74.

75. try{cn.close();}catch(Exception e){}*/

76.

77. try {

78.

79. if(cstmt != null)

80.

81. cstmt.close();

82.

83. if(cn != null)

84.

85. cn.close();

86.

87. } catch (SQLException e) {

88.

89. // TODO Auto-generated catch block

90.

91. e.printStackTrace();

92.

93. }

94.

95. }

96.

97. }


本文版權(quán)歸黑馬程序員JavaEE學(xué)院所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明作者出處。謝謝!

作者:黑馬程序員JavaEE培訓(xùn)學(xué)院

首發(fā):http://java.itheima.com/

分享到:
在線咨詢 我要報名
和我們在線交談!