Friday, July 18, 2014

Sử dụng stored procedure trong jdbc

 

Cấu trúc dữ liệu

1 IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Semester]') AND type in (N'U'))
2 DROP TABLE [dbo].[Semester]
3 GO
4
5 CREATE TABLE [dbo].[Semester](
6 [id] [int] NOT NULL,
7 [name] [nvarchar](50) NULL,
8 CONSTRAINT [PK_Semester] PRIMARY KEY CLUSTERED
9 (
10 [id] ASC
11 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
12 ) ON [PRIMARY]
13
14 GO
15
16 IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Subject]') AND type in (N'U'))
17 DROP TABLE [dbo].[Subject]
18 GO
19
20 CREATE TABLE [dbo].[Subject](
21 [id] [int] NOT NULL,
22 [sem_id] [int] NOT NULL,
23 [name] [nvarchar](50) NULL,
24 [duration] [int] NULL,
25 CONSTRAINT [PK_Subject] PRIMARY KEY CLUSTERED
26 (
27 [id] ASC,
28 [sem_id] ASC
29 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
30 ) ON [PRIMARY]
31
32 GO

Tạo một storeprocedure như sau


1 CREATE PROCEDURE ListAll
2 @Sem_id int
3 AS
4 BEGIN
5 SELECT * From Subject where sem_id = @Sem_id
6 END
7 GO

Như vậy chúng ta sẽ có được một thủ tục tên là “ListAll”. Đoạn mã sau dùng để gọi thực thi thủ tục trên


1 public void jdbcSQLServer() {
2 try {
3 // dang ky driver
4 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
5 Connection conn;
6 // thiet lap ke noi
7 conn = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=sa;database=java;");
8 // khoi tao loi goi thuc thi thu tuc
9 CallableStatement command = conn.prepareCall("{call ListAll (?)}");
10 // cung cap gia tro cho bien
11 command.setInt(1, 1);
12 ResultSet result = command.executeQuery();
13 // duyet ket qua
14 while (result.next()) {
15 System.out.print(result.getInt("id"));
16 System.out.println(" - " + result.getString("name"));
17 }
18 // dong ket noi
19 conn.close();
20 } catch (Exception ex) {
21 ex.printStackTrace();
22 }
23 }

Gọi thực thi đoạn mã trên chúng ta có kết quả sau


1 -  HTML
2 -  Java

====>>>> Bài tiếp theo chúng ta tìm hiểu Transaction trên jdbc.

No comments:

Post a Comment

Translate