Showing posts with label jdbc. Show all posts
Showing posts with label jdbc. Show all posts

Thursday, November 20, 2014

Mã hóa dữ liệu khi lưu trữ trong ứng dụng Java + SQL Server

Thông thường dữ liệu các nhân của người dùng khi lưu trữ vào csdl chúng ta nên che đi những dữ liệu nhạy cảm, trong ví dụ sau đây chúng ta cùng làm một demo nhỏ để che đi dữ liệu email và ngày sinh của người dùng (chỉ có ứng dụng của chúng ta mới giải mã được)

Tạo bảng để lưu được thông tin sau:
Order.    Name        Type
1.    Username    Text
2.    Password    Text
3.    Fullname    Text
4.    Address     Text
5.    Email       Text
6.    Birthdate   Date

Yêu cầu

Thiết kế form thêm thông tin người dùng vào bảng trên với các yêu cầu sau:
    1.    Mã hóa Password bằng giải thuật MD5
    2.    Mã hóa email và birthdate bằng giải thật mã hóa 02 chiều

Thiết kế form hiển thị ds người dùng thể hiện các cột: Username, Fullname và Address
Thiết kế form tìm người dùng dựa vào Username, kết quả hiển thị chi tiết người dùng gồm thông tin
       Username
    •    Fullname
    •    Address
    •    Email và Birthdate đã được giải mã

Giao diên thêm và tìm thông tin

image Dữ liệu đã mã hóa

image Dữ liệu được giải mã (nhấn nút find)

image

Bước 1: Tạo CSDL tên data và bảng nguoidung

1 SET ANSI_NULLS ON
2 GO
3
4 SET QUOTED_IDENTIFIER ON
5 GO
6
7 SET ANSI_PADDING ON
8 GO
9
10 CREATE TABLE [dbo].[users](
11 [username] [varchar](50) NULL,
12 [password] [varchar](100) NULL,
13 [fullname] [varchar](100) NULL,
14 [address] [varchar](250) NULL,
15 [email] [varbinary](max) NULL,
16 [birthdate] [varbinary](max) NULL
17 ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
18
19 GO
20
21 SET ANSI_PADDING OFF
22 GO

Bước 2: Tạo cập khóa cho ứng dụng và lưu trữ lại để sử dụng (file)


1 class KeyGen {
2 public static void main(String[] args) {
3 try {
4 if (!new File("src/lib/pri.key").exists()) {
5 KeyPairGenerator key = KeyPairGenerator.getInstance("RSA");
6 key.initialize(512);
7 KeyPair keys = key.genKeyPair();
8 // Tạo cặp khóa
9 PrivateKey privateKey = keys.getPrivate();
10 PublicKey publicKey = keys.getPublic();
11 // Lưu thông tin khóa để tái sử dụng, khóa công khai để giải mã
12 X509EncodedKeySpec x509EncodedKeySpec =
13 new X509EncodedKeySpec(publicKey.getEncoded());
14 FileOutputStream fos = new FileOutputStream("src/lib/pub.key");
15 fos.write(x509EncodedKeySpec.getEncoded());
16 fos.close();
17 // khóa mật để mã hóa
18 PKCS8EncodedKeySpec pkcs8EncodedKeySpec =
19 new PKCS8EncodedKeySpec(privateKey.getEncoded());
20 fos = new FileOutputStream("src/lib/pri.key");
21 fos.write(pkcs8EncodedKeySpec.getEncoded());
22 fos.close();
23 } else {
24 System.out.println("Khoa da co");
25 }
26 } catch (IOException ex) {
27 Logger.getLogger(KeyGen.class.getName()).log(Level.SEVERE, null, ex);
28 } catch (NoSuchAlgorithmException ex) {
29 Logger.getLogger(KeyGen.class.getName()).log(Level.SEVERE, null, ex);
30 }
31 }
32 }






Tới đây chúng ta đã có được cặp khóa để có thể mã hóa và giải mã những dữ liệu cần thiết.


Bước 3: Xây dựng lớp Encode để phục hồi khóa từ tập tin và tạo phương thức mã hóa, giải mã.



1 public class Encode {
2 private PrivateKey priKey;
3 private PublicKey pubKey;
4 public Encode() {
5 getKeys();
6 }
7 private void getKeys() {
8 try {
9 File pubKeyFile = new File("src/lib/pub.key");
10 File privKeyFile = new File("src/lib/pri.key");;
11 // đọc dữ liệu từ file và khởi tọa lại khóa công khai
12 DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
13 byte[] pubKeyBytes = new byte[(int) pubKeyFile.length()];
14 dis.readFully(pubKeyBytes);
15 dis.close();
16
17 // đọc dữ liệu từ file và khởi tọa lại khóa mật
18 dis = new DataInputStream(new FileInputStream(privKeyFile));
19 byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
20 dis.read(privKeyBytes);
21 dis.close();
22 //
23 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
24 // Tạo khóa công khai
25 X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
26 pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
27 // tạo khóa mật
28 PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
29 priKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
30 } catch (Exception ex) {
31 System.out.println("ERR: " + ex.toString());
32 }
33 }
34 // hàm mã hóa
35 public byte[] TwowayEncrypt(byte[] data) {
36 try {
37 Cipher c = Cipher.getInstance("RSA");
38 c.init(Cipher.ENCRYPT_MODE, priKey);
39 byte[] rs = c.doFinal(data);
40 return rs;
41 } catch (Exception ex) {
42 System.out.println("Err: " + ex.toString());
43 }
44 return null;
45 }
46 // hàm giải mã
47 public byte[] TwowayDecrypt(byte[] data) {
48 try {
49 Cipher c = Cipher.getInstance("RSA");
50 c.init(Cipher.DECRYPT_MODE, pubKey);
51 byte[] rs = c.doFinal(data);
52 return rs;
53 } catch (Exception ex) {
54 System.out.println("Err: " + ex.toString());
55 }
56 return null;
57 }
58 // dùng cho mã hóa mật khẩu
59 public byte[] OnewayEncrypt(byte[] data){
60 try {
61 MessageDigest dig = MessageDigest.getInstance("MD5");
62 return dig.digest(data);
63 } catch (Exception ex) {
64 System.out.println("ERR: "+ ex.toString());
65 }
66 return null;
67 }
68 }


Bước 4: Tích hợp lên giao diện


Xử lý sự kiện Click nút Add new


1 private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
2 try {
3 Connection conn = DriverManager.getConnection("jdbc:sqlserver://ntdan;databasename=data;", "sa", "sa");
4 PreparedStatement comm = conn.prepareStatement("Insert into users values(?,?,?,?,?,?)");
5 comm.setString(1, txtUser.getText());
6
7 byte[] ba1 = Charset.forName("UTF-8").encode(CharBuffer.wrap(txtPass.getPassword())).array();
8
9 comm.setString(2, new String(encode.OnewayEncrypt(ba1), "UTF-8"));
10 comm.setString(3, txtFull.getText());
11 comm.setString(4, txtAdd.getText());
12
13 comm.setBytes(5,encode.TwowayEncrypt(txtEmail.getText().getBytes("UTF-8")));
14 comm.setBytes(6, encode.TwowayEncrypt(txtBirth.getText().getBytes("UTF-8")));
15
16 comm.executeUpdate();
17 } catch (Exception ex) {
18 System.out.println("ERR: " + ex.toString());
19 }
20 }

Xử lý sự kiện Click nút Find


1 private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
2 try {
3 Connection conn = DriverManager.getConnection("jdbc:sqlserver://ntdan;databasename=data;", "sa", "sa");
4 PreparedStatement comm = conn.prepareStatement("Select * from Users where username=?");
5 comm.setString(1, txtUser.getText());
6 ResultSet rs = comm.executeQuery();
7 String found="";
8 if(rs.next())
9 {
10 found = "User: ";
11 found += rs.getString(1);
12 found += "\nFullname: "+rs.getString(3);
13 found += "\nAddress: "+rs.getString(4);
14 found += "\nEmail: "+ new String(encode.TwowayDecrypt(rs.getBytes(5)),"UTF-8");
15 found += "\nBirthDate: "+ new String(encode.TwowayDecrypt(rs.getBytes(6)),"UTF-8");
16 }
17
18 JOptionPane.showMessageDialog(this, found);
19 } catch (Exception ex) {
20 System.out.println("Err: "+ ex.toString());
21 }
22 }



OK, như vậy là cơ bản chúng ta đã một phần nào đó che đi dữ liệu email và ngày sinh khi lưu vào SQL Server.


 


Đây là một ví dụ nhỏ hi vọng sẽ giúp chúng ta có cái nhìn rất cơ bản về việc bảo vệ dữ liệu riêng tư cho ứng dụng.

Monday, November 10, 2014

JComboBox – Display and Value from Item

Do quá trình làm đồ án Java có nhiều bạn gặp khó khăn trong việc load dữ liệu vào JComboBox. Trong bài này tôi hướng dẫn một đoạn code nhỏ để các bạn tham khảo.

image

Bước 1: Định nghĩa nội dung cho một phần tử trong ds của JComboBox

1 class Item {
2 public Item(int id, String name, int price) {
3 this.id = id;
4 this.name = name;
5 this.price = price;
6 }
7
8 private int id;
9 private String name;
10 private int price;
11
12 public int getId() {
13 return id;
14 }
15
16 public void setId(int id) {
17 this.id = id;
18 }
19
20 public String getName() {
21 return name;
22 }
23
24 public void setName(String name) {
25 this.name = name;
26 }
27
28 @Override
29 public String toString() {
30 return getName() + "\t" + getPrice();
31 }
32
33 public int getPrice() {
34 return price;
35 }
36
37 public void setPrice(int price) {
38 this.price = price;
39 }
40 }
Bước 2: Gán dữ liệu vào danh sách và đưa lên JComboBox


1 private void load()
2 {
3 DefaultComboBoxModel model = new DefaultComboBoxModel();
4 model.addElement(new Item(1,"Mit",8000));
5 model.addElement(new Item(2,"Cam", 15000));
6 model.addElement(new Item(2,"Xoai", 20000));
7 jComboBox1.setModel(model);
8 }

Bước 3: Nhận giá trị (khóa, ID) của từ JComboBox khi chọn một phần từ từ giao diện


- Đăng ký sự kiện chọn phần tử từ ds





1 private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
2 this.setTitle( ((Item)jComboBox1.getSelectedItem()).getId()+"");
3 }


Tới đây chạy lại from để quan sát kết quả.


 


Mã nguồn tham khảo ở đây


http://1drv.ms/10JvXRm


Video tham khảo


http://youtu.be/wvJ155iuni0?list=UUQ8F8U5jZwjS4MZ5JYX5W2A

Friday, November 7, 2014

Một số câu hỏi ôn tập môn học DBSJ

 

Một số câu hỏi ôn lý thuyết

1. JDBC and ODBC are identical?
A. True
B. False
2. How many kinds of JDBC drivers?
A. 10
B. 3
C. 4
D. many
3. The JDBC API is a Java API for accessing virtually any kind of tabular data
A. False
B. True
4. What is the correct statement about CallableStatement interface? (choose 1)
A. It defines a statement to create a stored-procedure
B. It contains a call to a stored-procedure
C. It defines a store-procedure
5. Which is the default port number of RMI Registry Server?
A. 1023
B. 1099
C. 1069
6. Which of the following statements is correct for retrieving all fields from Student table?
A. String sql=”SELECT FROM Student”;
Statement st=cn.createStatement(sql);
ResultSet rs=st.executeQuery();
B. String sql=”SELECT FROM Student”;
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
7. If you need to use a stored procedure with output parameters, which of the following statement type should be used to call the procedure?
A. PreparedStatement
B. CallableStatement
C. Statement
8. From which object do you ask for DatabaseMetaData?
A. DriverManager
B. ResultSet
C. Connection
D. Driver
9. Which character is used to represent an input parameter in a CallableStatement?
A.
B. #
C. ?
D. %
10. Which one of the following will not get the data from the first column of ResultSet rs, returned from executing SQL statement: SELECT name, rank, serialNo FROM employee.
A. rs.getString(“name”);
B. rs.getString(1);
C. rs.getString(0);
11. Which class contains the transaction control method setAutoCommit, commit, and rollback?
A. Statement
B. Connection
C. ResultSet
12. You can use an applet in RMI program as ________
A. None of the other options
B. Server program
C. Client program
13. Which of the following will not cause a JDBC driver to be loaded and registered with the DriverManager?
A. Class.forName(driverString);
B. new DriverClass();
C. Include driver name in jdbc.drivers system property
D. None of the above
14. SQLWarnings from multiple Statement method calls (like executeUpdate) will build up until you ask for them all with getWarnings and getNextWarning.
A. True
B. False
15. If one intends to work with a ResultSet, which of these PreparedStatement methods will not work?
A. execute()
B. executeQuery()
C. executeUpdate()
16. Can a ResultSet be reliably returned from a method that creates a Statement and executes a query?
A. Yes
B. No
17. How can I use JDBC to create a database?
A. Include create=true at end of JDBC URL
B. Execute "CREATE DATABASE jGuru" SQL statement
C. Execute "STRSQL" and "CREATE COLLECTION jGuru" SQL statements
D. Database creation is DBMS specific
18. Which of the following can you do with a JDBC 2.0 database driver that you cannot with a JDBC 1.x driver?
A. Batch multiple statements, to be sent to the database together
B. Scroll through result sets bi-directionally
C. Work with SQL3 data types directly
D. All of the above
19. A __________ result set has a cursor that moves both forward and backward and can be moved to a particular row
A. scrollable
B. nonscrollable
C. Unscrollable
20. The method___________ is designed for statements that produce a single result set, such as SELECT statement
A. executeUpdate
B. execute
C. Update
D. executeQuery
21. Which three of the following are classes of Java.rmi package?
A. Naming
B. MarshalledObject
C. RMISecurityManager
D. Remote
22. Which option of jar file indicates manifest file not created?
A. Jar M
B. Jar t
c. Jar m
D. Jar c
23. _______ option of Jar command makes a Java archive file.
A. JAR -c
B. JAR -m
C. JAR -v
D. JAR –f
24. Which command adds the file file.class to Xyz.jar?
A. jar – uf Xyz . jar file.class
B. jar – xf Xyz . jar
C. jar – tf Xyz . jar
25. Driver types are used to categorize the technology used to connect to the database.
A. True
B. False
26. This is an Application Programming Interface provided by Microsoft for access the database.It uses SQL as its database language.
A. JDBC
B. ODBC
27. JDBC is ODBC translated into an object-oriented interface that is natural for java programmers.
A. True
B. False
28. In this Data processing Model,the client communicates directly to the database server without the help of any middle-ware technologies or another server.
A. Two-tier Data processing Model
B. Three - tier Data processing Model
29. The Type 1 driver is also known as JDBC-ODBC bridge plus ODBC driver.
A. Translates JDBC calls into ODBC calls.
B. Translates JDBC calls into database=specific calls or native calls
C. Maps JDBC calls to the underlying "network" protocol, which in turn calls native methods on the server.
D. Directly calls RDBMS from client machine.
30. This method is used to execute INSERT, DELETE, UPDATE , and other SQL DDL such as CREATE, DROP Table.
A. executeUpdate();
B. execute();
C. executeQuery();
31. This method is used for retrieving a string value (SQL type VARCHAR) and assigning into java String object.
A. getVarchar();
B. getObject();
C. getString();
32. This method is used for retrieving the value from current row as object.
A. getRow();
B. getObject();
C. getString();
33. This object connects to a data source only to read data from a ResultSet or write data back to the data source.
A. A Connected RowSet.
B. A Disconnected RowSet.
34. A client application uses stored procedures increases the network traffic, but it reduces the number of times a database is accessed.
A. True
B. False
35. This parameter is used to pass values into a store procedure.The value of this parameter cannot changed or reassigned within the module and hence is constant.
A. IN
B. OUT
C. IN/OUT
36. OUT Parameter. - 3 choices.
A. pass out of procedure module
B. is a constant
C. is a variable
D. back to the calling block
37. This Parameter behaves like an initialized variable.
A. OUT
B. IN
C. IN/OUT
38. This object does not contain the stored procedure itself but contains only a call to the stored procedure.
A. CallableStatment
B. PreparedStatment
C. prepareCall();
39. This refers to the ability to check whether the cursor stays open after a COMMIT
A. Updatable
B. Holdable
C. Scrollable
40. The prepareStatment() method sends SQL query to the database. and this returns:
A. PrepareStatment Object
B. Callalbalestatment Object
C. PrepareCall () method.
41. The CallableStatment object contains the SQL statments.
A. True
B. False
42. A cursor that can only be used to process from the beginning of a ResultSet to the end of it.It is default type.
A. TYPE_SCROLL_SENSITIVE
B. TYPE_SCROLL_INSENSITIVE
C. TYPE_FORWARD_ONLY
43. A Rowset Object provides scrollability and updatability for any kind of DBMS or drivers.
A. True
B. False
44. A ResultSet object contains a set of rows from a result set or some other source of tabular data, like a file or spreadsheet.
A. true
B. false
45. Which class is a disconnected rowset.
A. A CachedRowSet class.
B. A JDBCRowSet class.
C. A WebRowSet class.
46. Which statments are true?
A. A RowSet has to be make scrollable and updatable at the time of creation.
B. Scrollability and Updatability of a RowSet is independent of the JDBC driver
C. A connect RowSet can read data from a non relational database source also.
D. A RowSet is a JavaBeans component which has to programmatically notify all registered event listener.
47. The Result Set can not be modified and hence, It is not updatable in any way.
A. CONCURENT_READ_ONLY
B. CONCURENT_UPDATABLE
48. This is the mechanism of encoding information in a secret coded form, intented only for the recipient to access the information.
A. Cryptography
B. Encryption
49. The term "encrypting " pertains to converting plaintext to ciphertext, which is again decrypted into usable plaintext.
A. True
B. False
50. This transforms the input, called the plaintext, to an output, known as ciphertext. this is known as Symmetric cryptography.
A. Hash Function
B. Secret key cryptography
C. Public Key cryptography
51. This is as asymmetric cryptography, It operates under two different keys.
A. Public Key cryptography
B. Hash Function
C. Secret key cryptography
52. This is algorithms that does not use any key, it is known as message digest.
A. Secret key cryptography
B. Public Key cryptography
C. Hash Function
53. Which statements are true?
A. The Tamper-proofing process verifies whether the data received by the receiver is the same data as sent by the sender.
B. Spoofing or identity interception, which means impersonating the identity of a different user and use it in an unauthorized way
C. Authentication is the process that provides tamper-proofing, while it is on the network.
54. The class is use to hash value of the specified data.
A. Message Digest
B. Signature
C. KeyPair Generator
D. KeyFactory
E. Certificate Factory
55. The 'Native API-Java/Party Java' is Driver Type
A. I
B. II
C. III
D. IV
56. The 'Native Protocol - All Java' is Driver Type
A. I
B. II
C. III
D. IV
57. Statement and PreparedStatement is inherited from Statement Interface. The CallableStatement is inherited from PreparedStatement interface.
A. True
B. False
58. This Method return an Integer value indicating the row count.
A. ExecuteQuery();
B. Execute();
C. ExecuteUpdate();
59. If row value is 0, this method has no effect.If row value is positive, the cursor is moved forward that many row.
A. relative(int row) method
B. absolute(int row) method.
60. Calling absolute(1) is equivalent to calling last()
A. True
B. False
61. Which statements are true? (3 choices)
A. In Scrollable ResultSet, the cursor is positioned on the first row.
B. A default ResultSet object is not updated and has a cursor that moves forward only.
C. The ResultSet should be compulsorily closed after a COMMIT statement.
D. Holdable refers to ability to check whether the cursor stays open after a COMMIT.
E. The createStatement method has two argurments namely resultSetType and resultSetConcurrency
62. Which statements are true? (3 choices)
A. The original message text has to be transmitted separately since the content of a digitally signed message is altered irreversibly.
B. A Certification authority creates a signed certificate by encrypting the digitally signature with its private key.
C. The digital signature and sender's public key are appended to end of a message.
D. A recipient decrypts a signed signature using its own public key.
E. The integrity of a message cannot be ensure while using message digests
63. This comprises the mapping of one or more permissions with a class.
A. Security Manager
B. Policy File
C. Access Controller
64. The class is use to produce a pair of public and private keys appropriate for a specified.
A. Signature
B. Message Digest
C. KeyPair Generator
D. KeyFactory
E. Certificate Factory
65. The class is used to sign and check the authenticity of digital signature
A. Message Digest
B. Signature
C. Certificate Factory
D. KeyFactory
E. KeyPair Generator
66. The class is used to transform opaque keys of type Key into key specifications and provide transparent representations of the underlying key material and vice versa.
A. Message Digest
B. KeyPair Generator
C. Signature
D. KeyFactory
E. Certificate Factory
67. The class is used to generate public key certificates.
A. Certificate Factory
B. KeyPair Generator
C. Message Digest
D. Signature
E. KeyFactory
68. This class is a database of keys and certificates
A. Algorithm Parameters
B. KeyStore
C. Key
D. KeySpec
69. this ensures that a user or a business organization or a program entity has performed a transaction.
A. Non-repudiation
B. Tampering
C. Integrity
D. Confidentiality
70. Data integrity is to protect data from getting tampered, while it is on the network.
A. True
B. False
71. This is a framework written in java to access and develop cryptographic functionality, and forms part of the java security API.
A. JCA
B. JCE
72. With this padding technique a short block is padded with a repeating byte.
A. DES
B. PKCS5
C. CBC
73. Single-bit ciphers are called:
A. Block cipher
B. Stream cipher
74. Cipher objects are created using this method of the cipher class.
A. getInstance();
B. init();
75. the cipher object is initialized by the init() method?
A. True
B. False
76. The Code : "DES/CBC/PKCS5Padding" is the form of
A. "mode/algorithm/padding"
B. "algorithm/mode/padding"
C. "algorithm/padding/mode"
D. "DeCrypto/Cipher/padding"
77. "(Only)algorithm" such as
A. "DES"
B. "PKCS5"
C. "CBE"
78. Most these implementations mix a random number, known as the "salt" with the password text to derive an encrypted key.
A. Encryption and Decryption
B. Key Agreement
C. Password Base Encryption
79. Single bits or a block of bits can be encrypted into cipher blocks
A. True
B. False
80. In this Environment, the java application is the client and DBMS is the database server.
A. Three-Tier JDBC
B. Two-Tier JDBC

 

Đáp án:

1-B, 2-4,3-B,4-B,5-B,6-B,7-B, 8-C, 9-C, 10-C, 11-B, 12-C, 13-D, 14-B, 15-C, 16-B, 17-B, 18-D, 19-D, 20-D, 21-abc, 25-a, 26-b, 26-a, 27-a, 28-a, 29-a, 30-a, 31-c, 32-b, 33-a, 34-b, 35-a, 36-ad, 37-c, 38-a, 39-b, 40-a, 41-a, 42-c, 43-a, 44-b, 45a, 46b, 47a, 48a, 49a, 50b, 51a, 52c, 53a, 54a, 55a, 56c, 57a, 58c, 59a, 60b, 61ade, 62bce, 63b, 64c, 65b, 66d, 67a, 68b, 69a, 70a, 71a, 72b, 73b, 74a, 75a, 76b, 77a, 78c, 79a, 80b. 

Monday, July 28, 2014

Sử dụng Transaction trên JDBC

Như đã nêu ở bài trước bài này chúng ta sẽ làm ví dụ về quản lý Transaction và batch execute trên jdbc.

JDBC cho phép thực thì hàng loạt thao tác trong một lần gởi yêu cần về server dữ liệu (batch).

Chúng ta ví dụ thêm dữ liệu và 02 bảng đồng thời (Semester và Subject của bài trước).

1 Connection conn; 2 conn = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=sa;database=java;"); 3 // khoi tao transaction 4 conn.setAutoCommit(false); 5 Statement command = conn.createStatement(); 6 command.addBatch("insert into semester(id,name) values(1,'Semester 1')"); 7 command.addBatch("insert into subject(id,sem_id,name) values(1,1,'HTML')"); 8 command.addBatch("insert into subject(id,sem_id,name) values(2,1,'Java')"); 9 command.addBatch("insert into subject(id,sem_id,name) values(2,1,'csharpe')"); 10 command.executeBatch(); 11 // cap nhat thay doi du lieu ve server 12 conn.setAutoCommit(true);

Nhìn vào đoạn mã trên chúng ta thấy rằng sẽ có 03 dòng dữ liệu được thêm vào hệ thống nhưng dòng cuối cùng thì lỗi trùng khóa chính. Với lệnh

1 conn.setAutoCommit(false);

Chúng ta đã báo cho jdbc biết rằng những thay đổi mà chúng ta đã thực hiện thì chỉ được chấp nhận khi nào chúng ta gọi lệnh

1 conn.setAutoCommit(true);

Do đó, khi chạy ứng dụng chúng ta sẽ kg có dòng nào được thêm vào dữ liệu ở đây do dòng 09 phát sinh lỗi nên dòng 12 sẽ không được thực thi.

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.

Translate