更新時(shí)間:2018-01-23 來(lái)源:黑馬程序員 瀏覽量:
啥也不說(shuō),直接上代碼了!
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. //這里最好不要這么干,因?yàn)轵?qū)動(dòng)名寫(xiě)死在程序中了
34.
35. Class.forName("com.mysql.jdbc.Driver");
36.
37. //實(shí)際項(xiàng)目中,這里應(yīng)用DataSource數(shù)據(jù),如果用框架,
38.
39. //這個(gè)數(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第幾個(gè),不同的數(shù)據(jù)庫(kù)不一樣,建議不寫(xiě)
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)載請(qǐng)注明作者出處。謝謝!
作者:黑馬程序員JavaEE培訓(xùn)學(xué)院
首發(fā):http://java.itheima.com/